diff options
Diffstat (limited to 'lib/libc')
485 files changed, 15106 insertions, 12052 deletions
diff --git a/lib/libc/Makefile b/lib/libc/Makefile index b58b6cb..77c7ce0 100644 --- a/lib/libc/Makefile +++ b/lib/libc/Makefile @@ -5,6 +5,16 @@ SHLIBDIR?= /lib .include <bsd.own.mk> +# Pick the current architecture directory for libc. In general, this is +# named MACHINE_CPUARCH, but some ABIs are different enough to require +# their own libc, so allow a directory named MACHINE_ARCH to override this. + +.if exists(${.CURDIR}/${MACHINE_ARCH}) +LIBC_ARCH=${MACHINE_ARCH} +.else +LIBC_ARCH=${MACHINE_CPUARCH} +.endif + # All library objects contain FreeBSD revision strings by default; they may be # excluded as a space-saving measure. To produce a library that does # not contain these strings, add -DSTRIP_FBSDID (see <sys/cdefs.h>) to CFLAGS @@ -15,12 +25,17 @@ LIB=c SHLIB_MAJOR= 7 WARNS?= 2 CFLAGS+=-I${.CURDIR}/include -I${.CURDIR}/../../include -CFLAGS+=-I${.CURDIR}/${MACHINE_ARCH} +CFLAGS+=-I${.CURDIR}/${LIBC_ARCH} CFLAGS+=-DNLS CLEANFILES+=tags INSTALL_PIC_ARCHIVE= PRECIOUSLIB= +.ifndef NO_THREAD_STACK_UNWIND +CANCELPOINTS_CFLAGS=-fexceptions +CFLAGS+=${CANCELPOINTS_CFLAGS} +.endif + # # Only link with static libgcc.a (no libgcc_eh.a). # @@ -36,12 +51,15 @@ MDASM= MIASM= NOASM= -.include "${.CURDIR}/${MACHINE_ARCH}/Makefile.inc" +.include "${.CURDIR}/${LIBC_ARCH}/Makefile.inc" .include "${.CURDIR}/db/Makefile.inc" .include "${.CURDIR}/compat-43/Makefile.inc" .include "${.CURDIR}/gdtoa/Makefile.inc" .include "${.CURDIR}/gen/Makefile.inc" .include "${.CURDIR}/gmon/Makefile.inc" +.if ${MK_ICONV} != "no" +.include "${.CURDIR}/iconv/Makefile.inc" +.endif .include "${.CURDIR}/inet/Makefile.inc" .include "${.CURDIR}/isc/Makefile.inc" .include "${.CURDIR}/locale/Makefile.inc" @@ -49,9 +67,12 @@ NOASM= .include "${.CURDIR}/net/Makefile.inc" .include "${.CURDIR}/nls/Makefile.inc" .include "${.CURDIR}/posix1e/Makefile.inc" -.if ${MACHINE_ARCH} != "amd64" && \ - ${MACHINE_ARCH} != "ia64" && \ - ${MACHINE_ARCH} != "sparc64" +.if ${LIBC_ARCH} != "amd64" && \ + ${LIBC_ARCH} != "ia64" && \ + ${LIBC_ARCH} != "powerpc64" && \ + ${LIBC_ARCH} != "sparc64" && \ + ${MACHINE_ARCH:Mmipsn32*} == "" && \ + ${MACHINE_ARCH:Mmips64*} == "" .include "${.CURDIR}/quad/Makefile.inc" .endif .include "${.CURDIR}/regex/Makefile.inc" @@ -64,7 +85,7 @@ NOASM= .include "${.CURDIR}/rpc/Makefile.inc" .include "${.CURDIR}/uuid/Makefile.inc" .include "${.CURDIR}/xdr/Makefile.inc" -.if ${MACHINE_ARCH} == "arm" || ${MACHINE_ARCH} == "mips" +.if ${LIBC_ARCH} == "arm" || ${LIBC_ARCH} == "mips" .include "${.CURDIR}/softfloat/Makefile.inc" .endif .if ${MK_NIS} != "no" @@ -109,23 +130,25 @@ KQSRCS= adddi3.c anddi3.c ashldi3.c ashrdi3.c cmpdi2.c divdi3.c iordi3.c \ KSRCS= bcmp.c ffs.c ffsl.c fls.c flsl.c index.c mcount.c rindex.c \ strcat.c strcmp.c strcpy.c strlen.c strncpy.c -libkern: libkern.gen libkern.${MACHINE_ARCH} +libkern: libkern.gen libkern.${LIBC_ARCH} libkern.gen: ${KQSRCS} ${KSRCS} cp -p ${.CURDIR}/quad/quad.h ${.ALLSRC} ${DESTDIR}/sys/libkern -libkern.${MACHINE_ARCH}:: ${KMSRCS} +libkern.${LIBC_ARCH}:: ${KMSRCS} .if defined(KMSRCS) && !empty(KMSRCS) - cp -p ${.ALLSRC} ${DESTDIR}/sys/libkern/${MACHINE_ARCH} + cp -p ${.ALLSRC} ${DESTDIR}/sys/libkern/${LIBC_ARCH} .endif - + .include <bsd.lib.mk> # Disable warnings in contributed sources. -CWARNFLAGS:= ${.IMPSRC:Ngdtoa_*.c:C/^.+$/${CWARNFLAGS}/} +CWARNFLAGS:= ${.IMPSRC:Ngdtoa_*.c:C/^.+$/${CWARNFLAGS}/:C/^$/-w/} # XXX For now, we don't allow libc to be compiled with # -fstack-protector-all because it breaks rtld. We may want to make a librtld # in the future to circumvent this. SSP_CFLAGS:= ${SSP_CFLAGS:S/^-fstack-protector-all$/-fstack-protector/} # Disable stack protection for SSP symbols. SSP_CFLAGS:= ${.IMPSRC:N*/stack_protector.c:C/^.+$/${SSP_CFLAGS}/} +# Generate stack unwinding tables for cancellation points +CANCELPOINTS_CFLAGS:= ${.IMPSRC:Mcancelpoints_*:C/^.+$/${CANCELPOINTS_CFLAGS}/:C/^$//} diff --git a/lib/libc/amd64/gen/_setjmp.S b/lib/libc/amd64/gen/_setjmp.S index 38c3c6f..9035632 100644 --- a/lib/libc/amd64/gen/_setjmp.S +++ b/lib/libc/amd64/gen/_setjmp.S @@ -92,3 +92,5 @@ ENTRY(___longjmp) 1: movq %rcx,0(%rsp) ret END(___longjmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/gen/fabs.S b/lib/libc/amd64/gen/fabs.S index 8c0c8bf..2ace0f9 100644 --- a/lib/libc/amd64/gen/fabs.S +++ b/lib/libc/amd64/gen/fabs.S @@ -42,3 +42,5 @@ END(fabs) .data signbit: .quad 0x8000000000000000 + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/gen/modf.S b/lib/libc/amd64/gen/modf.S index 4fee38b..691aad8 100644 --- a/lib/libc/amd64/gen/modf.S +++ b/lib/libc/amd64/gen/modf.S @@ -87,3 +87,5 @@ ENTRY(modf) ret END(modf) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/gen/rfork_thread.S b/lib/libc/amd64/gen/rfork_thread.S index c34a940..9720e08 100644 --- a/lib/libc/amd64/gen/rfork_thread.S +++ b/lib/libc/amd64/gen/rfork_thread.S @@ -100,3 +100,5 @@ ENTRY(rfork_thread) jmp HIDENAME(cerror) #endif END(rfork_thread) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/gen/setjmp.S b/lib/libc/amd64/gen/setjmp.S index 41de587..1409f4c 100644 --- a/lib/libc/amd64/gen/setjmp.S +++ b/lib/libc/amd64/gen/setjmp.S @@ -110,3 +110,5 @@ ENTRY(__longjmp) 1: movq %rcx,0(%rsp) ret END(__longjmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/gen/sigsetjmp.S b/lib/libc/amd64/gen/sigsetjmp.S index 8da4867..438d440 100644 --- a/lib/libc/amd64/gen/sigsetjmp.S +++ b/lib/libc/amd64/gen/sigsetjmp.S @@ -111,3 +111,5 @@ ENTRY(__siglongjmp) 1: movq %rcx,0(%rsp) ret END(__siglongjmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/stdlib/div.S b/lib/libc/amd64/stdlib/div.S index f3c2a59..366010c 100644 --- a/lib/libc/amd64/stdlib/div.S +++ b/lib/libc/amd64/stdlib/div.S @@ -16,3 +16,5 @@ ENTRY(div) orq %rdx,%rax ret END(div) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/stdlib/ldiv.S b/lib/libc/amd64/stdlib/ldiv.S index 2a0a8cf..f11472c 100644 --- a/lib/libc/amd64/stdlib/ldiv.S +++ b/lib/libc/amd64/stdlib/ldiv.S @@ -14,3 +14,5 @@ ENTRY(ldiv) idivq %rsi ret END(ldiv) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/stdlib/lldiv.S b/lib/libc/amd64/stdlib/lldiv.S index e5ae5ca..4dab0fd 100644 --- a/lib/libc/amd64/stdlib/lldiv.S +++ b/lib/libc/amd64/stdlib/lldiv.S @@ -14,3 +14,5 @@ ENTRY(lldiv) idivq %rsi ret END(lldiv) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/string/bcmp.S b/lib/libc/amd64/string/bcmp.S index 375c3bc..d01b76b 100644 --- a/lib/libc/amd64/string/bcmp.S +++ b/lib/libc/amd64/string/bcmp.S @@ -23,3 +23,5 @@ L1: movsbl %al,%eax ret END(bcmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/string/bcopy.S b/lib/libc/amd64/string/bcopy.S index f7aa6d1..cc38f47 100644 --- a/lib/libc/amd64/string/bcopy.S +++ b/lib/libc/amd64/string/bcopy.S @@ -95,3 +95,5 @@ END(memmove) END(bcopy) #endif #endif + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/string/bzero.S b/lib/libc/amd64/string/bzero.S index 0de67d3..cf46a2a 100644 --- a/lib/libc/amd64/string/bzero.S +++ b/lib/libc/amd64/string/bzero.S @@ -42,3 +42,5 @@ L1: movq %rsi,%rcx /* zero remainder by bytes */ ret END(bzero) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/string/memcmp.S b/lib/libc/amd64/string/memcmp.S index a039b5b..66d64a0 100644 --- a/lib/libc/amd64/string/memcmp.S +++ b/lib/libc/amd64/string/memcmp.S @@ -40,3 +40,5 @@ L6: xorl %eax,%eax /* Perform unsigned comparison */ subl %edx,%eax ret END(memcmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/string/memset.S b/lib/libc/amd64/string/memset.S index ed8ba24..84d1562 100644 --- a/lib/libc/amd64/string/memset.S +++ b/lib/libc/amd64/string/memset.S @@ -59,3 +59,5 @@ L1: rep ret END(memset) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/string/strcat.S b/lib/libc/amd64/string/strcat.S index b241ffc..7b5a1dd 100644 --- a/lib/libc/amd64/string/strcat.S +++ b/lib/libc/amd64/string/strcat.S @@ -164,3 +164,5 @@ ENTRY(strcat) .Ldone: ret END(strcat) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/string/strcmp.S b/lib/libc/amd64/string/strcmp.S index 81f54cb..07009c1 100644 --- a/lib/libc/amd64/string/strcmp.S +++ b/lib/libc/amd64/string/strcmp.S @@ -72,3 +72,5 @@ ENTRY(strcmp) subq %rdx,%rax ret END(strcmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/string/strcpy.S b/lib/libc/amd64/string/strcpy.S index 8cafa12..5feb925 100644 --- a/lib/libc/amd64/string/strcpy.S +++ b/lib/libc/amd64/string/strcpy.S @@ -110,3 +110,5 @@ ENTRY(strcpy) .Ldone: ret END(strcpy) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/brk.S b/lib/libc/amd64/sys/brk.S index c25daff..2319417 100644 --- a/lib/libc/amd64/sys/brk.S +++ b/lib/libc/amd64/sys/brk.S @@ -83,3 +83,5 @@ err: jmp HIDENAME(cerror) #endif END(brk) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/cerror.S b/lib/libc/amd64/sys/cerror.S index 547a18c..d01cf4a 100644 --- a/lib/libc/amd64/sys/cerror.S +++ b/lib/libc/amd64/sys/cerror.S @@ -56,3 +56,4 @@ HIDENAME(cerror): movq $-1,%rdx ret + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/exect.S b/lib/libc/amd64/sys/exect.S index 93125fa..81dc8e5 100644 --- a/lib/libc/amd64/sys/exect.S +++ b/lib/libc/amd64/sys/exect.S @@ -54,3 +54,5 @@ ENTRY(exect) jmp HIDENAME(cerror) #endif END(exect) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/getcontext.S b/lib/libc/amd64/sys/getcontext.S index 08a6493..ea29adb 100644 --- a/lib/libc/amd64/sys/getcontext.S +++ b/lib/libc/amd64/sys/getcontext.S @@ -53,3 +53,5 @@ ENTRY(__sys_getcontext) jmp HIDENAME(cerror) #endif END(__sys_getcontext) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/pipe.S b/lib/libc/amd64/sys/pipe.S index a286064..59c1ac1c 100644 --- a/lib/libc/amd64/sys/pipe.S +++ b/lib/libc/amd64/sys/pipe.S @@ -58,3 +58,5 @@ ENTRY(__sys_pipe) jmp HIDENAME(cerror) #endif END(__sys_pipe) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/ptrace.S b/lib/libc/amd64/sys/ptrace.S index 29ebade..6235390 100644 --- a/lib/libc/amd64/sys/ptrace.S +++ b/lib/libc/amd64/sys/ptrace.S @@ -58,3 +58,5 @@ err: jmp HIDENAME(cerror) #endif END(ptrace) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/reboot.S b/lib/libc/amd64/sys/reboot.S index 59df944..e79ca79 100644 --- a/lib/libc/amd64/sys/reboot.S +++ b/lib/libc/amd64/sys/reboot.S @@ -55,3 +55,5 @@ ENTRY(__sys_reboot) jmp HIDENAME(cerror) #endif END(__sys_reboot) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/sbrk.S b/lib/libc/amd64/sys/sbrk.S index fed3882..3e4d8aa 100644 --- a/lib/libc/amd64/sys/sbrk.S +++ b/lib/libc/amd64/sys/sbrk.S @@ -86,3 +86,5 @@ err: jmp HIDENAME(cerror) #endif END(sbrk) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/setlogin.S b/lib/libc/amd64/sys/setlogin.S index 649289a..23692b9 100644 --- a/lib/libc/amd64/sys/setlogin.S +++ b/lib/libc/amd64/sys/setlogin.S @@ -63,3 +63,5 @@ ENTRY(__sys_setlogin) jmp HIDENAME(cerror) #endif END(__sys_setlogin) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/sigreturn.S b/lib/libc/amd64/sys/sigreturn.S index 28dc227..f91816e 100644 --- a/lib/libc/amd64/sys/sigreturn.S +++ b/lib/libc/amd64/sys/sigreturn.S @@ -44,3 +44,5 @@ __FBSDID("$FreeBSD$"); */ RSYSCALL(sigreturn) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/amd64/sys/vfork.S b/lib/libc/amd64/sys/vfork.S index d955e5f..555c3ca 100644 --- a/lib/libc/amd64/sys/vfork.S +++ b/lib/libc/amd64/sys/vfork.S @@ -57,3 +57,5 @@ ENTRY(__sys_vfork) jmp HIDENAME(cerror) #endif END(__sys_vfork) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/arm/gen/modf.c b/lib/libc/arm/gen/modf.c index 347090c..cb5aeac 100644 --- a/lib/libc/arm/gen/modf.c +++ b/lib/libc/arm/gen/modf.c @@ -86,7 +86,7 @@ modf(val, iptr) * 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 the fractional part is the part with the rest of the + * 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 diff --git a/lib/libc/compat-43/Makefile.inc b/lib/libc/compat-43/Makefile.inc index 8505ff2..867a9d9 100644 --- a/lib/libc/compat-43/Makefile.inc +++ b/lib/libc/compat-43/Makefile.inc @@ -2,7 +2,7 @@ # $FreeBSD$ # compat-43 sources -.PATH: ${.CURDIR}/${MACHINE_ARCH}/compat-43 ${.CURDIR}/compat-43 +.PATH: ${.CURDIR}/${LIBC_ARCH}/compat-43 ${.CURDIR}/compat-43 SRCS+= creat.c gethostid.c getwd.c killpg.c sethostid.c setpgrp.c \ setrgid.c setruid.c sigcompat.c diff --git a/lib/libc/compat-43/sigcompat.c b/lib/libc/compat-43/sigcompat.c index c3ba30a..199846f 100644 --- a/lib/libc/compat-43/sigcompat.c +++ b/lib/libc/compat-43/sigcompat.c @@ -35,6 +35,7 @@ __FBSDID("$FreeBSD$"); #include "namespace.h" #include <sys/param.h> +#include <errno.h> #include <signal.h> #include <string.h> #include "un-namespace.h" @@ -112,8 +113,10 @@ xsi_sigpause(int sig) { sigset_t set; - sigemptyset(&set); - sigaddset(&set, sig); + if (_sigprocmask(SIG_BLOCK, NULL, &set) == -1) + return (-1); + if (sigdelset(&set, sig) == -1) + return (-1); return (_sigsuspend(&set)); } @@ -123,7 +126,8 @@ sighold(int sig) sigset_t set; sigemptyset(&set); - sigaddset(&set, sig); + if (sigaddset(&set, sig) == -1) + return (-1); return (_sigprocmask(SIG_BLOCK, &set, NULL)); } @@ -143,7 +147,8 @@ sigrelse(int sig) sigset_t set; sigemptyset(&set); - sigaddset(&set, sig); + if (sigaddset(&set, sig) == -1) + return (-1); return (_sigprocmask(SIG_UNBLOCK, &set, NULL)); } @@ -152,35 +157,30 @@ void { sigset_t set, pset; struct sigaction sa, psa; - int error; sigemptyset(&set); - sigaddset(&set, sig); - error = _sigprocmask(SIG_BLOCK, NULL, &pset); - if (error == -1) + if (sigaddset(&set, sig) == -1) + return (SIG_ERR); + if (_sigprocmask(SIG_BLOCK, NULL, &pset) == -1) return (SIG_ERR); if ((__sighandler_t *)disp == SIG_HOLD) { - error = _sigprocmask(SIG_BLOCK, &set, &pset); - if (error == -1) + if (_sigprocmask(SIG_BLOCK, &set, &pset) == -1) return (SIG_ERR); if (sigismember(&pset, sig)) return (SIG_HOLD); else { - error = _sigaction(sig, NULL, &psa); - if (error == -1) + if (_sigaction(sig, NULL, &psa) == -1) return (SIG_ERR); return (psa.sa_handler); } } else { - error = _sigprocmask(SIG_UNBLOCK, &set, &pset); - if (error == -1) + if (_sigprocmask(SIG_UNBLOCK, &set, &pset) == -1) return (SIG_ERR); } bzero(&sa, sizeof(sa)); sa.sa_handler = disp; - error = _sigaction(sig, &sa, &psa); - if (error == -1) + if (_sigaction(sig, &sa, &psa) == -1) return (SIG_ERR); if (sigismember(&pset, sig)) return (SIG_HOLD); diff --git a/lib/libc/compat-43/sigpause.2 b/lib/libc/compat-43/sigpause.2 index bf3cf0b..1187b52 100644 --- a/lib/libc/compat-43/sigpause.2 +++ b/lib/libc/compat-43/sigpause.2 @@ -195,6 +195,7 @@ functions, an attempt was made to catch or ignore .Dv SIGKILL or .Dv SIGSTOP . +.El .Sh SEE ALSO .Xr kill 2 , .Xr sigaction 2 , @@ -237,5 +238,5 @@ function appeared in .Bx 4.2 and has been deprecated. All other functions appeared in -.Fx 9.0 +.Fx 8.1 and were deprecated before being implemented. diff --git a/lib/libc/db/hash/hash.c b/lib/libc/db/hash/hash.c index 83d2657..638814c 100644 --- a/lib/libc/db/hash/hash.c +++ b/lib/libc/db/hash/hash.c @@ -293,6 +293,8 @@ init_hash(HTAB *hashp, const char *file, const HASHINFO *info) if (stat(file, &statbuf)) return (NULL); hashp->BSIZE = statbuf.st_blksize; + if (hashp->BSIZE > MAX_BSIZE) + hashp->BSIZE = MAX_BSIZE; hashp->BSHIFT = __log2(hashp->BSIZE); } diff --git a/lib/libc/db/hash/hash.h b/lib/libc/db/hash/hash.h index 8329413..cd11a3a 100644 --- a/lib/libc/db/hash/hash.h +++ b/lib/libc/db/hash/hash.h @@ -118,7 +118,7 @@ typedef struct htab { /* Memory resident data structure */ /* * Constants */ -#define MAX_BSIZE 65536 /* 2^16 */ +#define MAX_BSIZE 32768 /* 2^15 but should be 65536 */ #define MIN_BUFFERS 6 #define MINHDRSIZE 512 #define DEF_BUFSIZE 65536 /* 64 K */ diff --git a/lib/libc/db/man/dbopen.3 b/lib/libc/db/man/dbopen.3 index 7ef7ae7..13481dd 100644 --- a/lib/libc/db/man/dbopen.3 +++ b/lib/libc/db/man/dbopen.3 @@ -28,7 +28,7 @@ .\" @(#)dbopen.3 8.5 (Berkeley) 1/2/94 .\" $FreeBSD$ .\" -.Dd January 2, 1994 +.Dd September 10, 2010 .Dt DBOPEN 3 .Os .Sh NAME @@ -78,8 +78,8 @@ arguments are as specified to the .Xr open 2 routine, however, only the -.Dv O_CREAT , O_EXCL , O_EXLOCK , O_NONBLOCK , -.Dv O_RDONLY , O_RDWR , O_SHLOCK +.Dv O_CREAT , O_EXCL , O_EXLOCK , O_NOFOLLOW , O_NONBLOCK , +.Dv O_RDONLY , O_RDWR , O_SHLOCK , O_SYNC and .Dv O_TRUNC flags are meaningful. diff --git a/lib/libc/db/man/hash.3 b/lib/libc/db/man/hash.3 index 6724042..133885d 100644 --- a/lib/libc/db/man/hash.3 +++ b/lib/libc/db/man/hash.3 @@ -78,7 +78,7 @@ The element defines the .Nm -table bucket size, and is, by default, 256 bytes. +table bucket size, and is, by default, 4096 bytes. It may be preferable to increase the page size for disk-resident tables and tables with large data items. .It Va ffactor diff --git a/lib/libc/gen/Makefile.inc b/lib/libc/gen/Makefile.inc index 2f562da..d55bc46 100644 --- a/lib/libc/gen/Makefile.inc +++ b/lib/libc/gen/Makefile.inc @@ -2,15 +2,15 @@ # $FreeBSD$ # machine-independent gen sources -.PATH: ${.CURDIR}/${MACHINE_ARCH}/gen ${.CURDIR}/gen +.PATH: ${.CURDIR}/${LIBC_ARCH}/gen ${.CURDIR}/gen SRCS+= __getosreldate.c __xuname.c \ _once_stub.c _pthread_stubs.c _rand48.c _spinlock_stub.c \ _thread_init.c \ - alarm.c arc4random.c assert.c basename.c check_utility_compat.c \ + alarm.c arc4random.c assert.c aux.c basename.c check_utility_compat.c \ clock.c closedir.c confstr.c \ crypt.c ctermid.c daemon.c devname.c dirname.c disklabel.c \ - dlfcn.c drand48.c erand48.c err.c errlst.c errno.c \ + dlfcn.c drand48.c elf_utils.c erand48.c err.c errlst.c errno.c \ exec.c fdevname.c feature_present.c fmtcheck.c fmtmsg.c fnmatch.c \ fpclassify.c frexp.c fstab.c ftok.c fts.c fts-compat.c ftw.c \ getbootfile.c getbsize.c \ @@ -25,7 +25,7 @@ SRCS+= __getosreldate.c __xuname.c \ pause.c pmadvise.c popen.c posix_spawn.c \ psignal.c pututxline.c pw_scan.c pwcache.c \ raise.c readdir.c readpassphrase.c rewinddir.c \ - scandir.c seed48.c seekdir.c sem.c sem_new.c semctl.c \ + scandir.c seed48.c seekdir.c semctl.c \ setdomainname.c sethostname.c setjmperr.c setmode.c \ setproctitle.c setprogname.c siginterrupt.c siglist.c signal.c \ sigsetops.c sleep.c srand48.c statvfs.c stringlist.c strtofflags.c \ @@ -35,12 +35,18 @@ SRCS+= __getosreldate.c __xuname.c \ usleep.c utime.c utxdb.c valloc.c vis.c wait.c wait3.c waitpid.c \ wordexp.c +CANCELPOINTS_SRCS=sem.c sem_new.c +.for src in ${CANCELPOINTS_SRCS} +SRCS+=cancelpoints_${src} +CLEANFILES+=cancelpoints_${src} +cancelpoints_${src}: + ln -sf ${.CURDIR}/gen/${src} ${.TARGET} +.endfor + SYM_MAPS+=${.CURDIR}/gen/Symbol.map # machine-dependent gen sources -.if exists(${.CURDIR}/${MACHINE_ARCH}/gen/Makefile.inc) -.include "${.CURDIR}/${MACHINE_ARCH}/gen/Makefile.inc" -.endif +.sinclude "${.CURDIR}/${LIBC_ARCH}/gen/Makefile.inc" MAN+= alarm.3 arc4random.3 \ basename.3 check_utility_compat.3 clock.3 \ @@ -129,7 +135,7 @@ MLINKS+=getusershell.3 endusershell.3 getusershell.3 setusershell.3 MLINKS+=getutxent.3 endutxent.3 getutxent.3 getutxid.3 \ getutxent.3 getutxline.3 getutxent.3 getutxuser.3 \ getutxent.3 pututxline.3 getutxent.3 setutxdb.3 \ - getutxent.3 setutxent.3 + getutxent.3 setutxent.3 getutxent.3 utmpx.3 MLINKS+=glob.3 globfree.3 MLINKS+=isgreater.3 isgreaterequal.3 isgreater.3 isless.3 \ isgreater.3 islessequal.3 isgreater.3 islessgreater.3 \ @@ -174,9 +180,9 @@ MLINKS+=syslog.3 closelog.3 syslog.3 openlog.3 syslog.3 setlogmask.3 \ syslog.3 vsyslog.3 MLINKS+=tcsendbreak.3 tcdrain.3 tcsendbreak.3 tcflow.3 tcsendbreak.3 tcflush.3 MLINKS+=tcsetattr.3 cfgetispeed.3 tcsetattr.3 cfgetospeed.3 \ - tcsetattr.3 cfmakeraw.3 tcsetattr.3 cfsetispeed.3 \ - tcsetattr.3 cfsetospeed.3 tcsetattr.3 cfsetspeed.3 \ - tcsetattr.3 tcgetattr.3 + tcsetattr.3 cfmakeraw.3 tcsetattr.3 cfmakesane.3 \ + tcsetattr.3 cfsetispeed.3 tcsetattr.3 cfsetospeed.3 \ + tcsetattr.3 cfsetspeed.3 tcsetattr.3 tcgetattr.3 MLINKS+=ttyname.3 isatty.3 ttyname.3 ttyname_r.3 MLINKS+=tzset.3 tzsetwall.3 MLINKS+=unvis.3 strunvis.3 unvis.3 strunvisx.3 diff --git a/lib/libc/gen/Symbol.map b/lib/libc/gen/Symbol.map index 42404bc..32cf92c 100644 --- a/lib/libc/gen/Symbol.map +++ b/lib/libc/gen/Symbol.map @@ -358,6 +358,7 @@ FBSD_1.1 { FBSD_1.2 { basename_r; + cfmakesane; endutxent; getpagesizes; getutxent; @@ -403,6 +404,8 @@ FBSDprivate_1.0 { _pthread_attr_setstackaddr; _pthread_attr_setstacksize; _pthread_cancel; + _pthread_cancel_enter; + _pthread_cancel_leave; _pthread_cleanup_pop; _pthread_cleanup_push; _pthread_cond_broadcast; @@ -446,10 +449,13 @@ FBSDprivate_1.0 { _spinlock; _spinlock_debug; _spinunlock; + _rtld_addr_phdr; _rtld_atfork_pre; _rtld_atfork_post; _rtld_error; /* for private use */ + _rtld_get_stack_prot; _rtld_thread_init; /* for private use */ + __elf_phdr_match_addr; _err; _warn; __fmtcheck; @@ -492,4 +498,7 @@ FBSDprivate_1.0 { _libc_sem_timedwait_compat; _libc_sem_post_compat; _libc_sem_getvalue_compat; + + __elf_aux_vector; + __pthread_map_stacks_exec; }; diff --git a/lib/libc/gen/__getosreldate.c b/lib/libc/gen/__getosreldate.c index 69aac07..980f9ef 100644 --- a/lib/libc/gen/__getosreldate.c +++ b/lib/libc/gen/__getosreldate.c @@ -29,6 +29,11 @@ __FBSDID("$FreeBSD$"); #include <sys/param.h> #include <sys/sysctl.h> +#include <errno.h> +#include <link.h> +#include "libc_private.h" + +int __getosreldate(void); /* * This is private to libc. It is intended for wrapping syscall stubs in order @@ -49,7 +54,11 @@ __getosreldate(void) if (osreldate != 0) return (osreldate); - + + error = _elf_aux_info(AT_OSRELDATE, &osreldate, sizeof(osreldate)); + if (error == 0 && osreldate != 0) + return (osreldate); + oid[0] = CTL_KERN; oid[1] = KERN_OSRELDATE; osrel = 0; diff --git a/lib/libc/gen/_pthread_stubs.c b/lib/libc/gen/_pthread_stubs.c index 044e299e..355b904 100644 --- a/lib/libc/gen/_pthread_stubs.c +++ b/lib/libc/gen/_pthread_stubs.c @@ -121,6 +121,8 @@ pthread_func_entry_t __thr_jtable[PJT_MAX] = { {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_TESTCANCEL */ {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_CLEANUP_POP_IMP */ {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_CLEANUP_PUSH_IMP */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_CANCEL_ENTER */ + {PJT_DUAL_ENTRY(stub_zero)}, /* PJT_CANCEL_LEAVE */ }; /* @@ -269,6 +271,8 @@ STUB_FUNC2(pthread_setcanceltype, PJT_SETCANCELTYPE, int, int, void *) STUB_FUNC(pthread_testcancel, PJT_TESTCANCEL, void) STUB_FUNC1(__pthread_cleanup_pop_imp, PJT_CLEANUP_POP_IMP, int, int) STUB_FUNC2(__pthread_cleanup_push_imp, PJT_CLEANUP_PUSH_IMP, void, void*, void *); +STUB_FUNC1(_pthread_cancel_enter, PJT_CANCEL_ENTER, int, int) +STUB_FUNC1(_pthread_cancel_leave, PJT_CANCEL_LEAVE, int, int) static int stub_zero(void) diff --git a/lib/libc/gen/_spinlock_stub.c b/lib/libc/gen/_spinlock_stub.c index a130c8e..47bbfeb 100644 --- a/lib/libc/gen/_spinlock_stub.c +++ b/lib/libc/gen/_spinlock_stub.c @@ -34,6 +34,11 @@ __FBSDID("$FreeBSD$"); #include "spinlock.h" +long _atomic_lock_stub(volatile long *); +void _spinlock_stub(spinlock_t *); +void _spinunlock_stub(spinlock_t *); +void _spinlock_debug_stub(spinlock_t *, char *, int); + /* * Declare weak definitions in case the application is not linked * with libpthread. @@ -43,12 +48,11 @@ __weak_reference(_spinlock_stub, _spinlock); __weak_reference(_spinunlock_stub, _spinunlock); __weak_reference(_spinlock_debug_stub, _spinlock_debug); - /* * This function is a stub for the _atomic_lock function in libpthread. */ long -_atomic_lock_stub(volatile long *lck) +_atomic_lock_stub(volatile long *lck __unused) { return (0L); } @@ -58,7 +62,7 @@ _atomic_lock_stub(volatile long *lck) * This function is a stub for the spinlock function in libpthread. */ void -_spinlock_stub(spinlock_t *lck) +_spinlock_stub(spinlock_t *lck __unused) { } @@ -66,7 +70,7 @@ _spinlock_stub(spinlock_t *lck) * This function is a stub for the spinunlock function in libpthread. */ void -_spinunlock_stub(spinlock_t *lck) +_spinunlock_stub(spinlock_t *lck __unused) { } @@ -74,6 +78,6 @@ _spinunlock_stub(spinlock_t *lck) * This function is a stub for the debug spinlock function in libpthread. */ void -_spinlock_debug_stub(spinlock_t *lck, char *fname, int lineno) +_spinlock_debug_stub(spinlock_t *lck __unused, char *fname __unused, int lineno __unused) { } diff --git a/lib/libc/gen/_thread_init.c b/lib/libc/gen/_thread_init.c index acaf65c..c0b6ade 100644 --- a/lib/libc/gen/_thread_init.c +++ b/lib/libc/gen/_thread_init.c @@ -29,8 +29,11 @@ __FBSDID("$FreeBSD$"); #include <sys/types.h> +void _thread_init_stub(void); + __weak_reference(_thread_init_stub, _thread_init); -__weak_reference(_thread_autoinit_dummy_decl_stub, _thread_autoinit_dummy_decl); +__weak_reference(_thread_autoinit_dummy_decl_stub, + _thread_autoinit_dummy_decl); int _thread_autoinit_dummy_decl_stub = 0; diff --git a/lib/libc/gen/alarm.3 b/lib/libc/gen/alarm.3 index 70e7c6e..92817b8 100644 --- a/lib/libc/gen/alarm.3 +++ b/lib/libc/gen/alarm.3 @@ -76,8 +76,7 @@ If no alarm is currently set, the return value is 0. .Sh SEE ALSO .Xr setitimer 2 , .Xr sigaction 2 , -.Xr sigpause 2 , -.Xr sigvec 2 , +.Xr sigsuspend 2 , .Xr signal 3 , .Xr sleep 3 , .Xr ualarm 3 , diff --git a/lib/libc/gen/aux.c b/lib/libc/gen/aux.c new file mode 100644 index 0000000..b5c079b --- /dev/null +++ b/lib/libc/gen/aux.c @@ -0,0 +1,146 @@ +/*- + * Copyright 2010 Konstantin Belousov <kib@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 ``AS IS'' AND ANY EXPRESS OR + * IMPLIED WARRANTIES, 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> +__FBSDID("$FreeBSD$"); + +#include "namespace.h" +#include <elf.h> +#include <errno.h> +#include <link.h> +#include <pthread.h> +#include <string.h> +#include "un-namespace.h" +#include "libc_private.h" + +Elf_Auxinfo *__elf_aux_vector; + +static pthread_once_t aux_once = PTHREAD_ONCE_INIT; + +static int pagesize, osreldate, canary_len, ncpus, pagesizes_len; +static char *canary, *pagesizes; + +static void +init_aux(void) +{ + Elf_Auxinfo *aux; + + for (aux = __elf_aux_vector; aux->a_type != AT_NULL; aux++) { + switch (aux->a_type) { + case AT_CANARY: + canary = (char *)(aux->a_un.a_ptr); + break; + + case AT_CANARYLEN: + canary_len = aux->a_un.a_val; + break; + + case AT_PAGESIZES: + pagesizes = (char *)(aux->a_un.a_ptr); + break; + + case AT_PAGESIZESLEN: + pagesizes_len = aux->a_un.a_val; + break; + + case AT_PAGESZ: + pagesize = aux->a_un.a_val; + break; + + case AT_OSRELDATE: + osreldate = aux->a_un.a_val; + break; + + case AT_NCPUS: + ncpus = aux->a_un.a_val; + break; + } + } +} + +int +_elf_aux_info(int aux, void *buf, int buflen) +{ + int res; + + if (__elf_aux_vector == NULL) + return (ENOSYS); + _once(&aux_once, init_aux); + + switch (aux) { + case AT_CANARY: + if (canary != NULL && canary_len >= buflen) { + memcpy(buf, canary, buflen); + memset(canary, 0, canary_len); + canary = NULL; + res = 0; + } else + res = ENOENT; + break; + case AT_PAGESIZES: + if (pagesizes != NULL && pagesizes_len >= buflen) { + memcpy(buf, pagesizes, buflen); + res = 0; + } else + res = ENOENT; + break; + + case AT_PAGESZ: + if (buflen == sizeof(int)) { + if (pagesize != 0) { + *(int *)buf = pagesize; + res = 0; + } else + res = ENOENT; + } else + res = EINVAL; + break; + case AT_OSRELDATE: + if (buflen == sizeof(int)) { + if (osreldate != 0) { + *(int *)buf = osreldate; + res = 0; + } else + res = ENOENT; + } else + res = EINVAL; + break; + case AT_NCPUS: + if (buflen == sizeof(int)) { + if (ncpus != 0) { + *(int *)buf = ncpus; + res = 0; + } else + res = ENOENT; + } else + res = EINVAL; + break; + default: + res = ENOENT; + break; + } + return (res); +} diff --git a/lib/libc/gen/check_utility_compat.3 b/lib/libc/gen/check_utility_compat.3 index 7a96bac..57638e5 100644 --- a/lib/libc/gen/check_utility_compat.3 +++ b/lib/libc/gen/check_utility_compat.3 @@ -29,8 +29,8 @@ .\" $FreeBSD$ .\" .Dd October 27, 2002 -.Os .Dt CHECK_UTILITY_COMPAT 3 +.Os .Sh NAME .Nm check_utility_compat .Nd "determine whether a utility should be compatible" diff --git a/lib/libc/gen/confstr.3 b/lib/libc/gen/confstr.3 index e97505f..9ca4250 100644 --- a/lib/libc/gen/confstr.3 +++ b/lib/libc/gen/confstr.3 @@ -77,9 +77,7 @@ has a value, up to The copied value is always null terminated. .Pp The available values are as follows: -.Pp .Bl -tag -width 6n -.Pp .It Li _CS_PATH Return a value for the .Ev PATH diff --git a/lib/libc/gen/daemon.c b/lib/libc/gen/daemon.c index ba2a542..b359a87 100644 --- a/lib/libc/gen/daemon.c +++ b/lib/libc/gen/daemon.c @@ -64,6 +64,10 @@ daemon(nochdir, noclose) case 0: break; default: + /* + * A fine point: _exit(0), not exit(0), to avoid triggering + * atexit(3) processing + */ _exit(0); } diff --git a/lib/libc/gen/directory.3 b/lib/libc/gen/directory.3 index 3be3fa8..992d2fc 100644 --- a/lib/libc/gen/directory.3 +++ b/lib/libc/gen/directory.3 @@ -207,15 +207,18 @@ see .Pp Sample code which searches a directory for entry ``name'' is: .Bd -literal -offset indent -len = strlen(name); dirp = opendir("."); -while ((dp = readdir(dirp)) != NULL) - if (dp->d_namlen == len && !strcmp(dp->d_name, name)) { +if (dirp == NULL) + return (ERROR); +len = strlen(name); +while ((dp = readdir(dirp)) != NULL) { + if (dp->d_namlen == len && strcmp(dp->d_name, name) == 0) { (void)closedir(dirp); - return FOUND; + return (FOUND); } +} (void)closedir(dirp); -return NOT_FOUND; +return (NOT_FOUND); .Ed .Sh SEE ALSO .Xr close 2 , diff --git a/lib/libc/gen/dladdr.3 b/lib/libc/gen/dladdr.3 index 414fa49..6566279 100644 --- a/lib/libc/gen/dladdr.3 +++ b/lib/libc/gen/dladdr.3 @@ -26,8 +26,8 @@ .\" $FreeBSD$ .\" .Dd February 5, 1998 -.Os .Dt DLADDR 3 +.Os .Sh NAME .Nm dladdr .Nd find the shared object containing a given address diff --git a/lib/libc/gen/dlfcn.c b/lib/libc/gen/dlfcn.c index 4be8847..b109cc9 100644 --- a/lib/libc/gen/dlfcn.c +++ b/lib/libc/gen/dlfcn.c @@ -30,11 +30,12 @@ __FBSDID("$FreeBSD$"); /* * Linkage to services provided by the dynamic linker. */ +#include <sys/mman.h> #include <dlfcn.h> #include <link.h> #include <stddef.h> -static const char sorry[] = "Service unavailable"; +static char sorry[] = "Service unavailable"; /* * For ELF, the dynamic linker directly resolves references to its @@ -69,7 +70,7 @@ dlclose(void *handle) } #pragma weak dlerror -const char * +char * dlerror(void) { return sorry; @@ -157,3 +158,20 @@ void _rtld_atfork_post(int *locks) { } + +#pragma weak _rtld_addr_phdr +int +_rtld_addr_phdr(const void *addr, struct dl_phdr_info *phdr_info) +{ + + return (0); +} + +#pragma weak _rtld_get_stack_prot +int +_rtld_get_stack_prot(void) +{ + + return (PROT_EXEC | PROT_READ | PROT_WRITE); +} + diff --git a/lib/libc/gen/dlinfo.3 b/lib/libc/gen/dlinfo.3 index 9433fb6..d00f074 100644 --- a/lib/libc/gen/dlinfo.3 +++ b/lib/libc/gen/dlinfo.3 @@ -26,8 +26,8 @@ .\" $FreeBSD$ .\" .Dd February 14, 2003 -.Os .Dt DLINFO 3 +.Os .Sh NAME .Nm dlinfo .Nd information about dynamically loaded object diff --git a/lib/libc/gen/dllockinit.3 b/lib/libc/gen/dllockinit.3 index 98d1074..be3e2ca 100644 --- a/lib/libc/gen/dllockinit.3 +++ b/lib/libc/gen/dllockinit.3 @@ -26,8 +26,8 @@ .\" $FreeBSD$ .\" .Dd July 5, 2000 -.Os .Dt DLLOCKINIT 3 +.Os .Sh NAME .Nm dllockinit .Nd register thread locking methods with the dynamic linker diff --git a/lib/libc/gen/dlopen.3 b/lib/libc/gen/dlopen.3 index 6488bef..3da9b6e 100644 --- a/lib/libc/gen/dlopen.3 +++ b/lib/libc/gen/dlopen.3 @@ -33,8 +33,8 @@ .\" $FreeBSD$ .\" .Dd July 7, 2009 -.Os .Dt DLOPEN 3 +.Os .Sh NAME .Nm dlopen , .Nm dlsym , @@ -52,7 +52,7 @@ .Fn dlsym "void * restrict handle" "const char * restrict symbol" .Ft dlfunc_t .Fn dlfunc "void * restrict handle" "const char * restrict symbol" -.Ft const char * +.Ft char * .Fn dlerror "void" .Ft int .Fn dlclose "void *handle" @@ -149,7 +149,7 @@ The same behaviour may be requested by option of the static linker .Xr ld 1 . .It Dv RTLD_NOLOAD -Ony return valid handle for the object if it is already loaded in +Only return valid handle for the object if it is already loaded in the process address space, otherwise .Dv NULL is returned. diff --git a/lib/libc/gen/elf_utils.c b/lib/libc/gen/elf_utils.c new file mode 100644 index 0000000..7bd7511 --- /dev/null +++ b/lib/libc/gen/elf_utils.c @@ -0,0 +1,74 @@ +/* + * Copyright (c) 2010 Konstantin Belousov <kib@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. Neither the name of the author nor the names of any co-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. + * + * $FreeBSD$ + */ + +#include <sys/types.h> +#include <sys/mman.h> +#include <sys/resource.h> +#include <sys/sysctl.h> +#include <link.h> +#include <stddef.h> + +int +__elf_phdr_match_addr(struct dl_phdr_info *phdr_info, void *addr) +{ + const Elf_Phdr *ph; + int i; + + for (i = 0; i < phdr_info->dlpi_phnum; i++) { + ph = &phdr_info->dlpi_phdr[i]; + if (ph->p_type != PT_LOAD || (ph->p_flags & PF_X) == 0) + continue; + if (phdr_info->dlpi_addr + ph->p_vaddr <= (uintptr_t)addr && + (uintptr_t)addr + sizeof(addr) < phdr_info->dlpi_addr + + ph->p_vaddr + ph->p_memsz) + break; + } + return (i != phdr_info->dlpi_phnum); +} + +#pragma weak __pthread_map_stacks_exec +void +__pthread_map_stacks_exec(void) +{ + int mib[2]; + struct rlimit rlim; + u_long usrstack; + size_t len; + + mib[0] = CTL_KERN; + mib[1] = KERN_USRSTACK; + len = sizeof(usrstack); + if (sysctl(mib, sizeof(mib) / sizeof(mib[0]), &usrstack, &len, NULL, 0) + == -1) + return; + if (getrlimit(RLIMIT_STACK, &rlim) == -1) + return; + mprotect((void *)(uintptr_t)(usrstack - rlim.rlim_cur), + rlim.rlim_cur, _rtld_get_stack_prot()); +} + diff --git a/lib/libc/gen/errlst.c b/lib/libc/gen/errlst.c index db6bfa2..d817823 100644 --- a/lib/libc/gen/errlst.c +++ b/lib/libc/gen/errlst.c @@ -36,7 +36,7 @@ __FBSDID("$FreeBSD$"); #include <stdio.h> const char *const sys_errlist[] = { - "Undefined error: 0", /* 0 - ENOERROR */ + "No error: 0", /* 0 - ENOERROR */ "Operation not permitted", /* 1 - EPERM */ "No such file or directory", /* 2 - ENOENT */ "No such process", /* 3 - ESRCH */ @@ -151,5 +151,6 @@ const char *const sys_errlist[] = { "Link has been severed", /* 91 - ENOLINK */ "Protocol error", /* 92 - EPROTO */ "Capabilities insufficient", /* 93 - ENOTCAPABLE */ + "Not permitted in capability mode", /* 94 - ECAPMODE */ }; const int sys_nerr = sizeof(sys_errlist) / sizeof(sys_errlist[0]); diff --git a/lib/libc/gen/feature_present.3 b/lib/libc/gen/feature_present.3 index 9a4269e..3a702d4 100644 --- a/lib/libc/gen/feature_present.3 +++ b/lib/libc/gen/feature_present.3 @@ -29,7 +29,7 @@ .\" $FreeBSD$ .\" .Dd January 8, 2008 -.Dt feature_present 3 +.Dt FEATURE_PRESENT 3 .Os .Sh NAME .Nm feature_present diff --git a/lib/libc/gen/fmtcheck.3 b/lib/libc/gen/fmtcheck.3 index ecd70fb..0bd4299 100644 --- a/lib/libc/gen/fmtcheck.3 +++ b/lib/libc/gen/fmtcheck.3 @@ -26,8 +26,8 @@ .\" .\" $FreeBSD$ .Dd October 16, 2002 -.Os .Dt FMTCHECK 3 +.Os .Sh NAME .Nm fmtcheck .Nd sanitizes user-supplied @@ -87,6 +87,12 @@ will return .Fa fmt_suspect . Otherwise, it will return .Fa fmt_default . +.Sh SEE ALSO +.Xr printf 3 +.Sh BUGS +The +.Fn fmtcheck +function does not recognize positional parameters. .Sh SECURITY CONSIDERATIONS Note that the formats may be quite different as long as they accept the same arguments. @@ -100,9 +106,3 @@ is not equivalent to .Qq Li %lx because the first requires an integer and the second requires a long. -.Sh SEE ALSO -.Xr printf 3 -.Sh BUGS -The -.Fn fmtcheck -function does not recognize positional parameters. diff --git a/lib/libc/gen/fnmatch.c b/lib/libc/gen/fnmatch.c index e697bdc..3acbc3b 100644 --- a/lib/libc/gen/fnmatch.c +++ b/lib/libc/gen/fnmatch.c @@ -67,7 +67,8 @@ __FBSDID("$FreeBSD$"); #define RANGE_ERROR (-1) static int rangematch(const char *, wchar_t, int, char **, mbstate_t *); -static int fnmatch1(const char *, const char *, int, mbstate_t, mbstate_t); +static int fnmatch1(const char *, const char *, const char *, int, mbstate_t, + mbstate_t); int fnmatch(pattern, string, flags) @@ -76,22 +77,21 @@ fnmatch(pattern, string, flags) { static const mbstate_t initial; - return (fnmatch1(pattern, string, flags, initial, initial)); + return (fnmatch1(pattern, string, string, flags, initial, initial)); } static int -fnmatch1(pattern, string, flags, patmbs, strmbs) - const char *pattern, *string; +fnmatch1(pattern, string, stringstart, flags, patmbs, strmbs) + const char *pattern, *string, *stringstart; int flags; mbstate_t patmbs, strmbs; { - const char *stringstart; char *newp; char c; wchar_t pc, sc; size_t pclen, sclen; - for (stringstart = string;;) { + for (;;) { pclen = mbrtowc(&pc, pattern, MB_LEN_MAX, &patmbs); if (pclen == (size_t)-1 || pclen == (size_t)-2) return (FNM_NOMATCH); @@ -145,8 +145,8 @@ fnmatch1(pattern, string, flags, patmbs, strmbs) /* General case, use recursion. */ while (sc != EOS) { - if (!fnmatch1(pattern, string, - flags & ~FNM_PERIOD, patmbs, strmbs)) + if (!fnmatch1(pattern, string, stringstart, + flags, patmbs, strmbs)) return (0); sclen = mbrtowc(&sc, string, MB_LEN_MAX, &strmbs); diff --git a/lib/libc/gen/frexp.3 b/lib/libc/gen/frexp.3 index 390da75..ba33d3d 100644 --- a/lib/libc/gen/frexp.3 +++ b/lib/libc/gen/frexp.3 @@ -70,7 +70,7 @@ such that is a .Vt double with magnitude in the interval -.Bo 1/2 , 1 Pc +.Eo [ 1/2 , 1 Ec ) or zero, and .Fa value equals diff --git a/lib/libc/gen/ftok.3 b/lib/libc/gen/ftok.3 index 78bfe45..996b2da 100644 --- a/lib/libc/gen/ftok.3 +++ b/lib/libc/gen/ftok.3 @@ -25,8 +25,8 @@ .\" .\" $FreeBSD$ .Dd July 9, 2009 -.Os .Dt FTOK 3 +.Os .Sh NAME .Nm ftok .Nd create IPC identifier from path name diff --git a/lib/libc/gen/fts-compat.c b/lib/libc/gen/fts-compat.c index 3afb87d..a6ddde4 100644 --- a/lib/libc/gen/fts-compat.c +++ b/lib/libc/gen/fts-compat.c @@ -110,6 +110,7 @@ struct _fts_private { static const char *ufslike_filesystems[] = { "ufs", + "zfs", "nfs", "nfs4", "ext2fs", diff --git a/lib/libc/gen/fts.c b/lib/libc/gen/fts.c index 1c547a1..f727003 100644 --- a/lib/libc/gen/fts.c +++ b/lib/libc/gen/fts.c @@ -100,6 +100,7 @@ struct _fts_private { static const char *ufslike_filesystems[] = { "ufs", + "zfs", "nfs", "nfs4", "ext2fs", diff --git a/lib/libc/gen/getcap.3 b/lib/libc/gen/getcap.3 index c6401f8..73826ae 100644 --- a/lib/libc/gen/getcap.3 +++ b/lib/libc/gen/getcap.3 @@ -305,15 +305,21 @@ 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 names optionally followed by a typed value: -.Bl -column "nameTvalue" -.It name Ta "typeless [boolean] capability" +.Pp +.Bl -tag -width "nameTvalue" -compact +.It name +typeless [boolean] capability .Em name No "is present [true]" -.It name Ns Em \&T Ns value Ta capability +.It name Ns Em \&T Ns value +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 +.It name@ +no capability +.Em name No exists +.It name Ns Em T Ns \&@ +capability .Pq Em name , T does not exist .El @@ -409,7 +415,6 @@ type `^') and any other value bindings are hidden. The capability abc also has two values bound but only a value of type `$' is prevented from being defined in the capability record more. -.Pp .Bd -unfilled -offset indent file1: new\||\|new_record\||\|a modification of "old":\e @@ -436,28 +441,24 @@ Two types are predefined by .Fn cgetnum and .Fn cgetstr : -.Bl -column "nameXnumber" -.Sm off -.It Em name No \&# Em number Ta numeric -.Sm on -capability +.Pp +.Bl -tag -width "nameXnumber" -compact +.It Em name Ns \&# Ns Em number +numeric capability .Em name has value .Em number -.Sm off -.It Em name No = Em string Ta "string capability" -.Sm on +.It Em name Ns = Ns Em string +string capability .Em name has value .Em string -.Sm off -.It Em name No \&#@ Ta "the numeric capability" -.Sm on +.It Em name Ns \&#@ +the numeric capability .Em name does not exist -.Sm off -.It Em name No \&=@ Ta "the string capability" -.Sm on +.It Em name Ns \&=@ +the string capability .Em name does not exist .El diff --git a/lib/libc/gen/getcwd.3 b/lib/libc/gen/getcwd.3 index 12a2bd6..88291c3 100644 --- a/lib/libc/gen/getcwd.3 +++ b/lib/libc/gen/getcwd.3 @@ -28,7 +28,7 @@ .\" @(#)getcwd.3 8.2 (Berkeley) 12/11/93 .\" $FreeBSD$ .\" -.Dd November 24, 1997 +.Dd April 17, 2010 .Dt GETCWD 3 .Os .Sh NAME @@ -108,8 +108,6 @@ The 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 @@ -124,6 +122,16 @@ The argument is greater than zero but smaller than the length of the pathname plus 1. .El +.Pp +The +.Fn getcwd +function +may fail if: +.Bl -tag -width Er +.It Bq Er EACCES +Read or search permission was denied for a component of the pathname. +This is only checked in limited cases, depending on implementation details. +.El .Sh SEE ALSO .Xr chdir 2 , .Xr fchdir 2 , diff --git a/lib/libc/gen/getdiskbyname.3 b/lib/libc/gen/getdiskbyname.3 index ed13539..4406096 100644 --- a/lib/libc/gen/getdiskbyname.3 +++ b/lib/libc/gen/getdiskbyname.3 @@ -54,7 +54,6 @@ the .Xr disktab 5 file. .Sh SEE ALSO -.Xr disklabel 5 , .Xr disktab 5 , .Xr disklabel 8 .Sh HISTORY diff --git a/lib/libc/gen/getosreldate.c b/lib/libc/gen/getosreldate.c index 086da6a..83bdc85 100644 --- a/lib/libc/gen/getosreldate.c +++ b/lib/libc/gen/getosreldate.c @@ -35,6 +35,7 @@ __FBSDID("$FreeBSD$"); #include <sys/param.h> #include <sys/sysctl.h> +#include <errno.h> #include <stdlib.h> #include <osreldate.h> @@ -45,15 +46,17 @@ getosreldate(void) int mib[2]; size_t size; int value; - char *temp; + if ((temp = getenv("OSVERSION"))) { + value = atoi(temp); + return (value); + } + mib[0] = CTL_KERN; mib[1] = KERN_OSRELDATE; size = sizeof value; if (sysctl(mib, 2, &value, &size, NULL, 0) == -1) return (-1); - if ((temp = getenv("OSVERSION"))) - value = atoi(temp); return (value); } diff --git a/lib/libc/gen/getpagesize.c b/lib/libc/gen/getpagesize.c index d796b9d..f4b8128 100644 --- a/lib/libc/gen/getpagesize.c +++ b/lib/libc/gen/getpagesize.c @@ -36,8 +36,12 @@ __FBSDID("$FreeBSD$"); #include <sys/param.h> #include <sys/sysctl.h> +#include <errno.h> +#include <link.h> #include <unistd.h> +#include "libc_private.h" + /* * This is unlikely to change over the running time of any * program, so we cache the result to save some syscalls. @@ -52,13 +56,20 @@ getpagesize() int mib[2]; static int value; size_t size; + int error; + + if (value != 0) + return (value); + + error = _elf_aux_info(AT_PAGESZ, &value, sizeof(value)); + if (error == 0 && value != 0) + return (value); + + mib[0] = CTL_HW; + mib[1] = HW_PAGESIZE; + size = sizeof value; + if (sysctl(mib, 2, &value, &size, NULL, 0) == -1) + return (-1); - if (!value) { - mib[0] = CTL_HW; - mib[1] = HW_PAGESIZE; - size = sizeof value; - if (sysctl(mib, 2, &value, &size, NULL, 0) == -1) - return (-1); - } return (value); } diff --git a/lib/libc/gen/getpagesizes.c b/lib/libc/gen/getpagesizes.c index b0de939..534fe9e 100644 --- a/lib/libc/gen/getpagesizes.c +++ b/lib/libc/gen/getpagesizes.c @@ -32,6 +32,9 @@ __FBSDID("$FreeBSD$"); #include <sys/sysctl.h> #include <errno.h> +#include <link.h> + +#include "libc_private.h" /* * Retrieves page size information from the system. Specifically, returns the @@ -51,7 +54,7 @@ getpagesizes(size_t pagesize[], int nelem) static u_long ps[MAXPAGESIZES]; static int nops; size_t size; - int i; + int error, i; if (nelem < 0 || (nelem > 0 && pagesize == NULL)) { errno = EINVAL; @@ -59,9 +62,13 @@ getpagesizes(size_t pagesize[], int nelem) } /* Cache the result of the sysctl(2). */ if (nops == 0) { + error = _elf_aux_info(AT_PAGESIZES, ps, sizeof(ps)); size = sizeof(ps); - if (sysctlbyname("hw.pagesizes", ps, &size, NULL, 0) == -1) - return (-1); + if (error != 0 || ps[0] == 0) { + if (sysctlbyname("hw.pagesizes", ps, &size, NULL, 0) + == -1) + return (-1); + } /* Count the number of page sizes that are supported. */ nops = size / sizeof(ps[0]); while (nops > 0 && ps[nops - 1] == 0) diff --git a/lib/libc/gen/getutxent.3 b/lib/libc/gen/getutxent.3 index 5ab21ee..5c8b793 100644 --- a/lib/libc/gen/getutxent.3 +++ b/lib/libc/gen/getutxent.3 @@ -24,9 +24,9 @@ .\" .\" $FreeBSD$ .\" -.Dd January 8, 2010 -.Os +.Dd February 19, 2011 .Dt GETUTXENT 3 +.Os .Sh NAME .Nm endutxent , .Nm getutxent , @@ -137,7 +137,7 @@ are not processed by this implementation. Other fields inside the structure are: .Bl -tag -width ut_user .It Fa ut_tv -The time the event occured. +The time the event occurred. This field is used for all types of entries, except .Dv EMPTY . .It Fa ut_id @@ -367,16 +367,15 @@ It returns .Dv NULL when the provided .Vt utmpx -is invalid. -This may be because -.Fa ut_type -is invalid or +is invalid, or .Fa ut_type has a value of .Dv DEAD_PROCESS and an entry with an identifier with a value equal to the field .Fa ut_id -was not found. +was not found; the global variable +.Va errno +is set to indicate the error. .Pp The .Fn setutxdb @@ -387,6 +386,24 @@ Otherwise, -1 is returned and the global variable is set to indicate the error. .Sh ERRORS In addition to the error conditions described in +.Xr fdopen 3 , +.Xr fopen 3 , +.Xr fseek 3 , +.Xr open 3 , +the +.Fn pututxline +function can generate the following errors: +.Bl -tag -width Er +.It Bq Er ESRCH +The value of +.Fa ut_type +is DEAD_PROCESS, and the process entry could not be found. +.It Bq Er EINVAL +The value of +.Fa ut_type +is not supported by this implementation. +.El +In addition to the error conditions described in .Xr fopen 3 , the .Fn setutxdb @@ -407,7 +424,8 @@ The file format is invalid. .Xr gettimeofday 2 , .Xr tty 4 , .Xr ac 8 , -.Xr newsyslog 8 +.Xr newsyslog 8 , +.Xr utxrm 8 .Sh STANDARDS The .Fn endutxent , diff --git a/lib/libc/gen/getutxent.c b/lib/libc/gen/getutxent.c index 654a634..556df56 100644 --- a/lib/libc/gen/getutxent.c +++ b/lib/libc/gen/getutxent.c @@ -112,22 +112,22 @@ getfutxent(struct futx *fu) if (udb == UTXDB_LOG) { uint16_t len; - if (fread(&len, sizeof len, 1, uf) != 1) + if (fread(&len, sizeof(len), 1, uf) != 1) return (-1); len = be16toh(len); if (len > sizeof *fu) { /* Forward compatibility. */ - if (fread(fu, sizeof *fu, 1, uf) != 1) + if (fread(fu, sizeof(*fu), 1, uf) != 1) return (-1); - fseek(uf, len - sizeof *fu, SEEK_CUR); + fseek(uf, len - sizeof(*fu), SEEK_CUR); } else { /* Partial record. */ - memset(fu, 0, sizeof *fu); + memset(fu, 0, sizeof(*fu)); if (fread(fu, len, 1, uf) != 1) return (-1); } } else { - if (fread(fu, sizeof *fu, 1, uf) != 1) + if (fread(fu, sizeof(*fu), 1, uf) != 1) return (-1); } return (0); @@ -163,7 +163,8 @@ getutxid(const struct utmpx *id) case LOGIN_PROCESS: case DEAD_PROCESS: if (memcmp(fu.fu_id, id->ut_id, - MIN(sizeof fu.fu_id, sizeof id->ut_id)) == 0) + MIN(sizeof(fu.fu_id), sizeof(id->ut_id))) == + 0) goto found; } break; @@ -191,7 +192,8 @@ getutxline(const struct utmpx *line) case USER_PROCESS: case LOGIN_PROCESS: if (strncmp(fu.fu_line, line->ut_line, - MIN(sizeof fu.fu_line, sizeof line->ut_line)) == 0) + MIN(sizeof(fu.fu_line), sizeof(line->ut_line))) == + 0) goto found; break; } @@ -212,7 +214,7 @@ getutxuser(const char *user) switch (fu.fu_type) { case USER_PROCESS: - if (strncmp(fu.fu_user, user, sizeof fu.fu_user) == 0) + if (strncmp(fu.fu_user, user, sizeof(fu.fu_user)) == 0) goto found; break; } diff --git a/lib/libc/gen/glob.3 b/lib/libc/gen/glob.3 index 4c912bb..7d6e43b 100644 --- a/lib/libc/gen/glob.3 +++ b/lib/libc/gen/glob.3 @@ -30,7 +30,7 @@ .\" @(#)glob.3 8.3 (Berkeley) 4/16/94 .\" $FreeBSD$ .\" -.Dd September 1, 2004 +.Dd February 15, 2011 .Dt GLOB 3 .Os .Sh NAME @@ -417,7 +417,7 @@ execvp("ls", g.gl_pathv); .Sh SEE ALSO .Xr sh 1 , .Xr fnmatch 3 , -.Xr regexp 3 +.Xr regex 3 .Sh STANDARDS The current implementation of the .Fn glob diff --git a/lib/libc/gen/glob.c b/lib/libc/gen/glob.c index 32af5db..c3d9f08 100644 --- a/lib/libc/gen/glob.c +++ b/lib/libc/gen/glob.c @@ -433,9 +433,9 @@ static int glob0(const Char *pattern, glob_t *pglob, size_t *limit) { const Char *qpatnext; - int c, err; + int err; size_t oldpathc; - Char *bufnext, patbuf[MAXPATHLEN]; + Char *bufnext, c, patbuf[MAXPATHLEN]; qpatnext = globtilde(pattern, patbuf, MAXPATHLEN, pglob); oldpathc = pglob->gl_pathc; diff --git a/lib/libc/gen/isgreater.3 b/lib/libc/gen/isgreater.3 index 0106155..9a6d85c 100644 --- a/lib/libc/gen/isgreater.3 +++ b/lib/libc/gen/isgreater.3 @@ -1,4 +1,4 @@ -.\" Copyright (c) 2003 David Schultz <das@FreeBSD.ORG> +.\" Copyright (c) 2003 David Schultz <das@FreeBSD.org> .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without diff --git a/lib/libc/gen/opendir.c b/lib/libc/gen/opendir.c index b312c89..0c08735 100644 --- a/lib/libc/gen/opendir.c +++ b/lib/libc/gen/opendir.c @@ -86,7 +86,7 @@ __opendir2(const char *name, int flags) errno = ENOTDIR; return (NULL); } - if ((fd = _open(name, O_RDONLY | O_NONBLOCK)) == -1) + if ((fd = _open(name, O_RDONLY | O_NONBLOCK | O_DIRECTORY)) == -1) return (NULL); return __opendir_common(fd, name, flags); @@ -200,7 +200,7 @@ __opendir_common(int fd, const char *name, int flags) */ if (flags & DTF_REWIND) { (void)_close(fd); - if ((fd = _open(name, O_RDONLY)) == -1) { + if ((fd = _open(name, O_RDONLY | O_DIRECTORY)) == -1) { saved_errno = errno; free(buf); free(dirp); diff --git a/lib/libc/gen/psignal.3 b/lib/libc/gen/psignal.3 index 5ad6ee2..5986ffa 100644 --- a/lib/libc/gen/psignal.3 +++ b/lib/libc/gen/psignal.3 @@ -28,7 +28,7 @@ .\" @(#)psignal.3 8.2 (Berkeley) 2/27/95 .\" $FreeBSD$ .\" -.Dd February 27, 1995 +.Dd February 4, 2011 .Dt PSIGNAL 3 .Os .Sh NAME @@ -89,7 +89,7 @@ indexed by recognized signal numbers. The external array .Va sys_signame is used similarly and -contains short, lower-case abbreviations for signals +contains short, upper-case abbreviations for signals which are useful for recognizing signal names in user input. The defined variable diff --git a/lib/libc/gen/pututxline.c b/lib/libc/gen/pututxline.c index ce4dc28..4caa00c 100644 --- a/lib/libc/gen/pututxline.c +++ b/lib/libc/gen/pututxline.c @@ -31,6 +31,7 @@ __FBSDID("$FreeBSD$"); #include <sys/endian.h> #include <sys/stat.h> #include <sys/uio.h> +#include <errno.h> #include <fcntl.h> #include <stdio.h> #include <string.h> @@ -42,9 +43,9 @@ __FBSDID("$FreeBSD$"); static FILE * futx_open(const char *file) { - int fd; FILE *fp; struct stat sb; + int fd; fd = _open(file, O_CREAT|O_RDWR|O_EXLOCK, 0644); if (fd < 0) @@ -53,6 +54,7 @@ futx_open(const char *file) /* Safety check: never use broken files. */ if (_fstat(fd, &sb) != -1 && sb.st_size % sizeof(struct futx) != 0) { _close(fd); + errno = EFTYPE; return (NULL); } @@ -61,16 +63,19 @@ futx_open(const char *file) _close(fd); return (NULL); } - return (fp); } -static void +static int utx_active_add(const struct futx *fu) { FILE *fp; struct futx fe; - off_t partial = -1; + off_t partial; + int error, ret; + + partial = -1; + ret = 0; /* * Register user login sessions. Overwrite entries of sessions @@ -78,16 +83,17 @@ utx_active_add(const struct futx *fu) */ fp = futx_open(_PATH_UTX_ACTIVE); if (fp == NULL) - return; - while (fread(&fe, sizeof fe, 1, fp) == 1) { + return (-1); + while (fread(&fe, sizeof(fe), 1, fp) == 1) { switch (fe.fu_type) { case USER_PROCESS: case INIT_PROCESS: case LOGIN_PROCESS: case DEAD_PROCESS: /* Overwrite when ut_id matches. */ - if (memcmp(fu->fu_id, fe.fu_id, sizeof fe.fu_id) == 0) { - fseeko(fp, -(off_t)sizeof fe, SEEK_CUR); + if (memcmp(fu->fu_id, fe.fu_id, sizeof(fe.fu_id)) == + 0) { + ret = fseeko(fp, -(off_t)sizeof(fe), SEEK_CUR); goto exact; } if (fe.fu_type != DEAD_PROCESS) @@ -95,21 +101,35 @@ utx_active_add(const struct futx *fu) /* FALLTHROUGH */ default: /* Allow us to overwrite unused records. */ - if (partial == -1) - partial = ftello(fp) - (off_t)sizeof fe; + if (partial == -1) { + partial = ftello(fp); + /* + * Distinguish errors from valid values so we + * don't overwrite good data by accident. + */ + if (partial != -1) + partial -= (off_t)sizeof(fe); + } break; } } - + /* * No exact match found. Use the partial match. If no partial * match was found, just append a new record. */ if (partial != -1) - fseeko(fp, partial, SEEK_SET); + ret = fseeko(fp, partial, SEEK_SET); exact: - fwrite(fu, sizeof *fu, 1, fp); + if (ret == -1) + error = errno; + else if (fwrite(fu, sizeof(*fu), 1, fp) < 1) + error = errno; + else + error = 0; fclose(fp); + errno = error; + return (error == 0 ? 0 : 1); } static int @@ -117,31 +137,37 @@ utx_active_remove(struct futx *fu) { FILE *fp; struct futx fe; + int error, ret; /* * Remove user login sessions, having the same ut_id. */ fp = futx_open(_PATH_UTX_ACTIVE); if (fp == NULL) - return (0); - while (fread(&fe, sizeof fe, 1, fp) == 1) { + return (-1); + error = ESRCH; + ret = -1; + while (fread(&fe, sizeof(fe), 1, fp) == 1 && ret != 0) switch (fe.fu_type) { case USER_PROCESS: case INIT_PROCESS: case LOGIN_PROCESS: - if (memcmp(fu->fu_id, fe.fu_id, sizeof fe.fu_id) != 0) + if (memcmp(fu->fu_id, fe.fu_id, sizeof(fe.fu_id)) != 0) continue; /* Terminate session. */ - fseeko(fp, -(off_t)sizeof fe, SEEK_CUR); - fwrite(fu, sizeof *fu, 1, fp); - fclose(fp); - return (0); + if (fseeko(fp, -(off_t)sizeof(fe), SEEK_CUR) == -1) + error = errno; + else if (fwrite(fu, sizeof(*fu), 1, fp) < 1) + error = errno; + else + ret = 0; + } - } fclose(fp); - return (1); + errno = error; + return (ret); } static void @@ -151,11 +177,14 @@ utx_active_purge(void) truncate(_PATH_UTX_ACTIVE, 0); } -static void +static int utx_lastlogin_add(const struct futx *fu) { - FILE *fp; struct futx fe; + FILE *fp; + int error, ret; + + ret = 0; /* * Write an entry to lastlogin. Overwrite the entry if the @@ -164,24 +193,31 @@ utx_lastlogin_add(const struct futx *fu) */ fp = futx_open(_PATH_UTX_LASTLOGIN); if (fp == NULL) - return; + return (-1); while (fread(&fe, sizeof fe, 1, fp) == 1) { if (strncmp(fu->fu_user, fe.fu_user, sizeof fe.fu_user) != 0) continue; - + /* Found a previous lastlogin entry for this user. */ - fseeko(fp, -(off_t)sizeof fe, SEEK_CUR); + ret = fseeko(fp, -(off_t)sizeof fe, SEEK_CUR); break; } - fwrite(fu, sizeof *fu, 1, fp); + if (ret == -1) + error = errno; + else if (fwrite(fu, sizeof *fu, 1, fp) < 1) { + error = errno; + ret = -1; + } fclose(fp); + errno = error; + return (ret); } static void utx_lastlogin_upgrade(void) { - int fd; struct stat sb; + int fd; fd = _open(_PATH_UTX_LASTLOGIN, O_RDWR, 0644); if (fd < 0) @@ -197,12 +233,12 @@ utx_lastlogin_upgrade(void) _close(fd); } -static void +static int utx_log_add(const struct futx *fu) { - int fd; - uint16_t l; struct iovec vec[2]; + int error, fd; + uint16_t l; /* * Append an entry to the log file. We only need to append @@ -210,27 +246,35 @@ utx_log_add(const struct futx *fu) * zero-bytes. Prepend a length field, indicating the length of * the record, excluding the length field itself. */ - for (l = sizeof *fu; l > 0 && ((const char *)fu)[l - 1] == '\0'; l--); + for (l = sizeof(*fu); l > 0 && ((const char *)fu)[l - 1] == '\0'; l--) ; vec[0].iov_base = &l; - vec[0].iov_len = sizeof l; + vec[0].iov_len = sizeof(l); vec[1].iov_base = __DECONST(void *, fu); vec[1].iov_len = l; l = htobe16(l); fd = _open(_PATH_UTX_LOG, O_CREAT|O_WRONLY|O_APPEND, 0644); if (fd < 0) - return; - _writev(fd, vec, 2); + return (-1); + if (_writev(fd, vec, 2) == -1) + error = errno; + else + error = 0; _close(fd); + errno = error; + return (error == 0 ? 0 : 1); } struct utmpx * pututxline(const struct utmpx *utmpx) { struct futx fu; + int bad; + + bad = 0; utx_to_futx(utmpx, &fu); - + switch (fu.fu_type) { case BOOT_TIME: case SHUTDOWN_TIME: @@ -241,23 +285,29 @@ pututxline(const struct utmpx *utmpx) case NEW_TIME: break; case USER_PROCESS: - utx_active_add(&fu); - utx_lastlogin_add(&fu); + bad |= utx_active_add(&fu); + bad |= utx_lastlogin_add(&fu); break; #if 0 /* XXX: Are these records of any use to us? */ case INIT_PROCESS: case LOGIN_PROCESS: - utx_active_add(&fu); + bad |= utx_active_add(&fu); break; #endif case DEAD_PROCESS: + /* + * In case writing a logout entry fails, never attempt + * to write it to utx.log. The logout entry's ut_id + * might be invalid. + */ if (utx_active_remove(&fu) != 0) return (NULL); break; default: + errno = EINVAL; return (NULL); } - utx_log_add(&fu); - return (futx_to_utx(&fu)); + bad |= utx_log_add(&fu); + return (bad ? NULL : futx_to_utx(&fu)); } diff --git a/lib/libc/gen/raise.3 b/lib/libc/gen/raise.3 index 5f422c5..fe75268 100644 --- a/lib/libc/gen/raise.3 +++ b/lib/libc/gen/raise.3 @@ -32,12 +32,12 @@ .\" @(#)raise.3 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd June 4, 1993 +.Dd May 7, 2010 .Dt RAISE 3 .Os .Sh NAME .Nm raise -.Nd send a signal to the current process +.Nd send a signal to the current thread .Sh LIBRARY .Lb libc .Sh SYNOPSIS @@ -49,7 +49,7 @@ The .Fn raise function sends the signal .Fa sig -to the current process. +to the current thread. .Sh RETURN VALUES .Rv -std raise .Sh ERRORS diff --git a/lib/libc/gen/readpassphrase.3 b/lib/libc/gen/readpassphrase.3 index 0d6a7ff..3bcee6f 100644 --- a/lib/libc/gen/readpassphrase.3 +++ b/lib/libc/gen/readpassphrase.3 @@ -1,33 +1,26 @@ -.\" $OpenBSD: readpassphrase.3,v 1.7 2001/12/15 15:37:51 millert Exp $ +.\" $OpenBSD: readpassphrase.3,v 1.17 2007/05/31 19:19:28 jmc Exp $ .\" -.\" Copyright (c) 2000 Todd C. Miller <Todd.Miller@courtesan.com> -.\" All rights reserved. +.\" Copyright (c) 2000, 2002 Todd C. Miller <Todd.Miller@courtesan.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. -.\" 3. The name of the author may not be used to endorse or promote products -.\" derived from this software without specific prior written permission. +.\" 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. .\" -.\" 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. +.\" 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. .\" .\" $FreeBSD$ .\" -.Dd December 7, 2001 +.Dd May 31, 2007 .Dt READPASSPHRASE 3 .Os .Sh NAME @@ -79,6 +72,8 @@ force input to lower case force input to upper case .It Dv RPP_SEVENBIT strip the high bit from input +.It Dv RPP_STDIN +force read of passphrase from stdin .El .Pp The calling process should zero the passphrase as soon as possible to @@ -87,7 +82,7 @@ space. .Sh RETURN VALUES Upon successful completion, .Fn readpassphrase -returns a pointer to the null-terminated passphrase. +returns a pointer to the NUL-terminated passphrase. If an error is encountered, the terminal state is restored and a .Dv NULL @@ -117,40 +112,6 @@ if (compare(transform(passbuf), epass) != 0) memset(passbuf, 0, sizeof(passbuf)); .Ed -.Sh SIGNALS -The -.Fn readpassphrase -function -will catch the following signals: -.Pp -.Bl -tag -compact -.It Dv SIGINT -.It Dv SIGHUP -.It Dv SIGQUIT -.It Dv SIGTERM -.It Dv SIGTSTP -.It Dv SIGTTIN -.It Dv SIGTTOU -.El -.Pp -When one of the above signals is intercepted, terminal echo will -be restored if it had previously been turned off. -If a signal handler was installed for the signal when -.Fn readpassphrase -was called that handler is then executed. -If no handler was previously installed for the signal then the -default action is taken as per -.Xr sigaction 2 . -.Pp -The -.Dv SIGTSTP , SIGTTIN , -and -.Dv SIGTTOU -signals (stop signal generated from keyboard or due to terminal I/O -from a background process) are treated specially. -When the process is resumed after it has been stopped, -.Fn readpassphrase -will reprint the prompt and the user may then enter a passphrase. .Sh ERRORS .Bl -tag -width Er .It Bq Er EINTR @@ -159,14 +120,14 @@ The function was interrupted by a signal. .It Bq Er EINVAL The -.Fa bufsiz +.Ar bufsiz argument was zero. .It Bq Er EIO The process is a member of a background process attempting to read from its controlling terminal, the process is ignoring or blocking the .Dv SIGTTIN -signal or the process group is orphaned. +signal, or the process group is orphaned. .It Bq Er EMFILE The process has already reached its limit for open file descriptors. .It Bq Er ENFILE @@ -176,6 +137,35 @@ There is no controlling terminal and the .Dv RPP_REQUIRE_TTY flag was specified. .El +.Sh SIGNALS +The +.Fn readpassphrase +function +will catch the following signals: +.Bd -literal -offset indent +SIGALRM SIGHUP SIGINT +SIGPIPE SIGQUIT SIGTERM +SIGTSTP SIGTTIN SIGTTOU +.Ed +.Pp +When one of the above signals is intercepted, terminal echo will +be restored if it had previously been turned off. +If a signal handler was installed for the signal when +.Fn readpassphrase +was called, that handler is then executed. +If no handler was previously installed for the signal then the +default action is taken as per +.Xr sigaction 2 . +.Pp +The +.Dv SIGTSTP , SIGTTIN +and +.Dv SIGTTOU +signals (stop signals generated from keyboard or due to terminal I/O +from a background process) are treated specially. +When the process is resumed after it has been stopped, +.Fn readpassphrase +will reprint the prompt and the user may then enter a passphrase. .Sh SEE ALSO .Xr sigaction 2 , .Xr getpass 3 diff --git a/lib/libc/gen/readpassphrase.c b/lib/libc/gen/readpassphrase.c index 983e01d..d57e703 100644 --- a/lib/libc/gen/readpassphrase.c +++ b/lib/libc/gen/readpassphrase.c @@ -1,35 +1,26 @@ -/* $OpenBSD: readpassphrase.c,v 1.12 2001/12/15 05:41:00 millert Exp $ */ +/* $OpenBSD: readpassphrase.c,v 1.23 2010/05/14 13:30:34 millert Exp $ */ /* - * Copyright (c) 2000 Todd C. Miller <Todd.Miller@courtesan.com> - * All rights reserved. + * Copyright (c) 2000-2002, 2007, 2010 + * Todd C. Miller <Todd.Miller@courtesan.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. - * 3. The name of the author may not be used to endorse or promote products - * derived from this software without specific prior written permission. + * 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. * - * 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. + * 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. */ -#if defined(LIBC_SCCS) && !defined(lint) -static const char rcsid[] = "$OpenBSD: readpassphrase.c,v 1.12 2001/12/15 05:41:00 millert Exp $"; -#endif /* LIBC_SCCS and not lint */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); @@ -46,7 +37,7 @@ __FBSDID("$FreeBSD$"); #include <readpassphrase.h> #include "un-namespace.h" -static volatile sig_atomic_t signo; +static volatile sig_atomic_t signo[NSIG]; static void handler(int); @@ -54,11 +45,11 @@ char * readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags) { ssize_t nr; - int input, output, save_errno; + int input, output, save_errno, i, need_restart; char ch, *p, *end; struct termios term, oterm; - struct sigaction sa, saveint, savehup, savequit, saveterm; - struct sigaction savetstp, savettin, savettou; + struct sigaction sa, savealrm, saveint, savehup, savequit, saveterm; + struct sigaction savetstp, savettin, savettou, savepipe; /* I suppose we could alloc on demand in this case (XXX). */ if (bufsiz == 0) { @@ -67,11 +58,17 @@ readpassphrase(const char *prompt, char *buf, size_t bufsiz, int flags) } restart: + for (i = 0; i < NSIG; i++) + signo[i] = 0; + nr = -1; + save_errno = 0; + need_restart = 0; /* * Read and write to /dev/tty if available. If not, read from * stdin and write to stderr unless a tty is required. */ - if ((input = output = _open(_PATH_TTY, O_RDWR)) == -1) { + if ((flags & RPP_STDIN) || + (input = output = _open(_PATH_TTY, O_RDWR)) == -1) { if (flags & RPP_REQUIRE_TTY) { errno = ENOTTY; return(NULL); @@ -81,45 +78,55 @@ restart: } /* + * Turn off echo if possible. + * If we are using a tty but are not the foreground pgrp this will + * generate SIGTTOU, so do it *before* installing the signal handlers. + */ + if (input != STDIN_FILENO && tcgetattr(input, &oterm) == 0) { + memcpy(&term, &oterm, sizeof(term)); + if (!(flags & RPP_ECHO_ON)) + term.c_lflag &= ~(ECHO | ECHONL); + if (term.c_cc[VSTATUS] != _POSIX_VDISABLE) + term.c_cc[VSTATUS] = _POSIX_VDISABLE; + (void)tcsetattr(input, TCSAFLUSH|TCSASOFT, &term); + } else { + memset(&term, 0, sizeof(term)); + term.c_lflag |= ECHO; + memset(&oterm, 0, sizeof(oterm)); + oterm.c_lflag |= ECHO; + } + + /* * Catch signals that would otherwise cause the user to end * up with echo turned off in the shell. Don't worry about - * things like SIGALRM and SIGPIPE for now. + * things like SIGXCPU and SIGVTALRM for now. */ sigemptyset(&sa.sa_mask); sa.sa_flags = 0; /* don't restart system calls */ sa.sa_handler = handler; - (void)_sigaction(SIGINT, &sa, &saveint); + (void)_sigaction(SIGALRM, &sa, &savealrm); (void)_sigaction(SIGHUP, &sa, &savehup); + (void)_sigaction(SIGINT, &sa, &saveint); + (void)_sigaction(SIGPIPE, &sa, &savepipe); (void)_sigaction(SIGQUIT, &sa, &savequit); (void)_sigaction(SIGTERM, &sa, &saveterm); (void)_sigaction(SIGTSTP, &sa, &savetstp); (void)_sigaction(SIGTTIN, &sa, &savettin); (void)_sigaction(SIGTTOU, &sa, &savettou); - /* Turn off echo if possible. */ - if (tcgetattr(input, &oterm) == 0) { - memcpy(&term, &oterm, sizeof(term)); - if (!(flags & RPP_ECHO_ON)) - term.c_lflag &= ~(ECHO | ECHONL); - if (term.c_cc[VSTATUS] != _POSIX_VDISABLE) - term.c_cc[VSTATUS] = _POSIX_VDISABLE; - (void)tcsetattr(input, TCSAFLUSH|TCSASOFT, &term); - } else { - memset(&term, 0, sizeof(term)); - memset(&oterm, 0, sizeof(oterm)); - } - - (void)_write(output, prompt, strlen(prompt)); + if (!(flags & RPP_STDIN)) + (void)_write(output, prompt, strlen(prompt)); end = buf + bufsiz - 1; - for (p = buf; (nr = _read(input, &ch, 1)) == 1 && ch != '\n' && ch != '\r';) { + p = buf; + while ((nr = _read(input, &ch, 1)) == 1 && ch != '\n' && ch != '\r') { if (p < end) { if ((flags & RPP_SEVENBIT)) ch &= 0x7f; if (isalpha(ch)) { if ((flags & RPP_FORCELOWER)) - ch = tolower(ch); + ch = (char)tolower(ch); if ((flags & RPP_FORCEUPPER)) - ch = toupper(ch); + ch = (char)toupper(ch); } *p++ = ch; } @@ -130,11 +137,16 @@ restart: (void)_write(output, "\n", 1); /* Restore old terminal settings and signals. */ - if (memcmp(&term, &oterm, sizeof(term)) != 0) - (void)tcsetattr(input, TCSANOW|TCSASOFT, &oterm); - (void)_sigaction(SIGINT, &saveint, NULL); + if (memcmp(&term, &oterm, sizeof(term)) != 0) { + while (tcsetattr(input, TCSAFLUSH|TCSASOFT, &oterm) == -1 && + errno == EINTR && !signo[SIGTTOU]) + continue; + } + (void)_sigaction(SIGALRM, &savealrm, NULL); (void)_sigaction(SIGHUP, &savehup, NULL); + (void)_sigaction(SIGINT, &saveint, NULL); (void)_sigaction(SIGQUIT, &savequit, NULL); + (void)_sigaction(SIGPIPE, &savepipe, NULL); (void)_sigaction(SIGTERM, &saveterm, NULL); (void)_sigaction(SIGTSTP, &savetstp, NULL); (void)_sigaction(SIGTTIN, &savettin, NULL); @@ -146,18 +158,22 @@ restart: * If we were interrupted by a signal, resend it to ourselves * now that we have restored the signal handlers. */ - if (signo) { - kill(getpid(), signo); - switch (signo) { - case SIGTSTP: - case SIGTTIN: - case SIGTTOU: - signo = 0; - goto restart; + for (i = 0; i < NSIG; i++) { + if (signo[i]) { + kill(getpid(), i); + switch (i) { + case SIGTSTP: + case SIGTTIN: + case SIGTTOU: + need_restart = 1; + } } } + if (need_restart) + goto restart; - errno = save_errno; + if (save_errno) + errno = save_errno; return(nr == -1 ? NULL : buf); } @@ -174,5 +190,5 @@ getpass(const char *prompt) static void handler(int s) { - signo = s; + signo[s] = 1; } diff --git a/lib/libc/gen/rfork_thread.3 b/lib/libc/gen/rfork_thread.3 index e985e1c..dfd6fbc 100644 --- a/lib/libc/gen/rfork_thread.3 +++ b/lib/libc/gen/rfork_thread.3 @@ -25,7 +25,7 @@ .\" .\" $FreeBSD$ .\" -.Dd July 29, 2000 +.Dd February 6, 2011 .Dt RFORK_THREAD 3 .Os .Sh NAME @@ -38,6 +38,13 @@ .Ft pid_t .Fn rfork_thread "int flags" "void *stack" "int (*func)(void *arg)" "void *arg" .Sh DESCRIPTION +.Bf -symbolic +The +.Fn rfork_thread +function has been deprecated in favor of +.Xr pthread_create 3 . +.Ef +.Pp The .Fn rfork_thread function @@ -71,7 +78,8 @@ for error return codes. .Xr intro 2 , .Xr minherit 2 , .Xr rfork 2 , -.Xr vfork 2 +.Xr vfork 2 , +.Xr pthread_create 3 .Sh HISTORY The .Fn rfork_thread diff --git a/lib/libc/gen/scandir.3 b/lib/libc/gen/scandir.3 index e32b0d8..b3e0a7e 100644 --- a/lib/libc/gen/scandir.3 +++ b/lib/libc/gen/scandir.3 @@ -40,7 +40,7 @@ .Sh SYNOPSIS .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 struct dirent **, const struct dirent **\\*(rp" +.Fn scandir "const char *dirname" "struct dirent ***namelist" "int \*(lp*select\*(rp\*(lpconst struct dirent *\*(rp" "int \*(lp*compar\*(rp\*(lpconst struct dirent **, const struct dirent **\*(rp" .Ft int .Fn alphasort "const struct dirent **d1" "const struct dirent **d2" .Sh DESCRIPTION diff --git a/lib/libc/gen/sem.c b/lib/libc/gen/sem.c index 628e650..e9ae669 100644 --- a/lib/libc/gen/sem.c +++ b/lib/libc/gen/sem.c @@ -312,21 +312,6 @@ _libc_sem_unlink_compat(const char *name) } static int -enable_async_cancel(void) -{ - int old; - - _pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old); - return (old); -} - -static void -restore_async_cancel(int val) -{ - _pthread_setcanceltype(val, NULL); -} - -static int _umtx_wait_uint(volatile unsigned *mtx, unsigned id, const struct timespec *timeout) { if (timeout && (timeout->tv_sec < 0 || (timeout->tv_sec == 0 && @@ -371,15 +356,15 @@ _libc_sem_timedwait_compat(sem_t * __restrict sem, const struct timespec * __restrict abstime) { struct timespec ts, ts2; - int val, retval, saved_cancel; + int val, retval; if (sem_check_validity(sem) != 0) return (-1); if ((*sem)->syssem != 0) { - saved_cancel = enable_async_cancel(); - retval = ksem_wait((*sem)->semid); - restore_async_cancel(saved_cancel); + _pthread_cancel_enter(1); + retval = ksem_wait((*sem)->semid); /* XXX no timeout */ + _pthread_cancel_leave(retval == -1); return (retval); } @@ -390,8 +375,10 @@ _libc_sem_timedwait_compat(sem_t * __restrict sem, if (atomic_cmpset_acq_int(&(*sem)->count, val, val - 1)) return (0); } - if (retval) + if (retval) { + _pthread_testcancel(); break; + } if (abstime) { if (abstime->tv_nsec >= 1000000000 || abstime->tv_nsec < 0) { errno = EINVAL; @@ -402,9 +389,9 @@ _libc_sem_timedwait_compat(sem_t * __restrict sem, } atomic_add_int(&(*sem)->nwaiters, 1); pthread_cleanup_push(sem_cancel_handler, sem); - saved_cancel = enable_async_cancel(); + _pthread_cancel_enter(1); retval = _umtx_wait_uint(&(*sem)->count, 0, abstime ? &ts2 : NULL); - restore_async_cancel(saved_cancel); + _pthread_cancel_leave(0); pthread_cleanup_pop(0); atomic_add_int(&(*sem)->nwaiters, -1); } diff --git a/lib/libc/gen/sem_new.c b/lib/libc/gen/sem_new.c index ef4ba68..2698b40 100644 --- a/lib/libc/gen/sem_new.c +++ b/lib/libc/gen/sem_new.c @@ -47,6 +47,7 @@ #include <semaphore.h> #include <unistd.h> #include "un-namespace.h" +#include "libc_private.h" __weak_reference(_sem_close, sem_close); __weak_reference(_sem_destroy, sem_destroy); @@ -364,15 +365,6 @@ _sem_trywait(sem_t *sem) return (-1); } -static void -sem_cancel_handler(void *arg) -{ - sem_t *sem = arg; - - if (sem->_kern._has_waiters && sem->_kern._count) - usem_wake(&sem->_kern); -} - #define TIMESPEC_SUB(dst, src, val) \ do { \ (dst)->tv_sec = (src)->tv_sec - (val)->tv_sec; \ @@ -384,27 +376,12 @@ sem_cancel_handler(void *arg) } while (0) -static __inline int -enable_async_cancel(void) -{ - int old; - - _pthread_setcanceltype(PTHREAD_CANCEL_ASYNCHRONOUS, &old); - return (old); -} - -static __inline void -restore_async_cancel(int val) -{ - _pthread_setcanceltype(val, NULL); -} - int _sem_timedwait(sem_t * __restrict sem, const struct timespec * __restrict abstime) { struct timespec ts, ts2; - int val, retval, saved_cancel; + int val, retval; if (sem_check_validity(sem) != 0) return (-1); @@ -416,8 +393,10 @@ _sem_timedwait(sem_t * __restrict sem, return (0); } - if (retval) + if (retval) { + _pthread_testcancel(); break; + } /* * The timeout argument is only supposed to @@ -431,11 +410,9 @@ _sem_timedwait(sem_t * __restrict sem, clock_gettime(CLOCK_REALTIME, &ts); TIMESPEC_SUB(&ts2, abstime, &ts); } - pthread_cleanup_push(sem_cancel_handler, sem); - saved_cancel = enable_async_cancel(); + _pthread_cancel_enter(1); retval = usem_wait(&sem->_kern, abstime ? &ts2 : NULL); - restore_async_cancel(saved_cancel); - pthread_cleanup_pop(0); + _pthread_cancel_leave(0); } return (retval); } diff --git a/lib/libc/gen/sem_timedwait.3 b/lib/libc/gen/sem_timedwait.3 index c2aca53..3a58d41 100644 --- a/lib/libc/gen/sem_timedwait.3 +++ b/lib/libc/gen/sem_timedwait.3 @@ -1,4 +1,4 @@ -.\" Copyright (c) 2008, David Xu <davidxu@freebsd.org> +.\" Copyright (c) 2008, David Xu <davidxu@FreeBSD.org> .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without diff --git a/lib/libc/gen/setproctitle.3 b/lib/libc/gen/setproctitle.3 index fe9f19a..0fefddf 100644 --- a/lib/libc/gen/setproctitle.3 +++ b/lib/libc/gen/setproctitle.3 @@ -1,4 +1,4 @@ -.\" Copyright (c) 1995 Peter Wemm <peter@freebsd.org> +.\" Copyright (c) 1995 Peter Wemm <peter@FreeBSD.org> .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without @@ -21,8 +21,8 @@ .\" .\" The following requests are required for all man pages. .Dd December 16, 1995 -.Os .Dt SETPROCTITLE 3 +.Os .Sh NAME .Nm setproctitle .Nd set process title diff --git a/lib/libc/gen/siginterrupt.3 b/lib/libc/gen/siginterrupt.3 index e5eae62..e790132 100644 --- a/lib/libc/gen/siginterrupt.3 +++ b/lib/libc/gen/siginterrupt.3 @@ -109,9 +109,8 @@ is not a valid signal number. .El .Sh SEE ALSO .Xr sigaction 2 , -.Xr sigblock 2 , -.Xr sigpause 2 , -.Xr sigsetmask 2 , +.Xr sigprocmask 2 , +.Xr sigsuspend 2 , .Xr signal 3 .Sh HISTORY The diff --git a/lib/libc/gen/siglist.c b/lib/libc/gen/siglist.c index 1ff1337..d4abfaa 100644 --- a/lib/libc/gen/siglist.c +++ b/lib/libc/gen/siglist.c @@ -37,37 +37,37 @@ __FBSDID("$FreeBSD$"); const char *const sys_signame[NSIG] = { "Signal 0", - "hup", /* SIGHUP */ - "int", /* SIGINT */ - "quit", /* SIGQUIT */ - "ill", /* SIGILL */ - "trap", /* SIGTRAP */ - "abrt", /* SIGABRT */ - "emt", /* SIGEMT */ - "fpe", /* SIGFPE */ - "kill", /* SIGKILL */ - "bus", /* SIGBUS */ - "segv", /* SIGSEGV */ - "sys", /* SIGSYS */ - "pipe", /* SIGPIPE */ - "alrm", /* SIGALRM */ - "term", /* SIGTERM */ - "urg", /* SIGURG */ - "stop", /* SIGSTOP */ - "tstp", /* SIGTSTP */ - "cont", /* SIGCONT */ - "chld", /* SIGCHLD */ - "ttin", /* SIGTTIN */ - "ttou", /* SIGTTOU */ - "io", /* SIGIO */ - "xcpu", /* SIGXCPU */ - "xfsz", /* SIGXFSZ */ - "vtalrm", /* SIGVTALRM */ - "prof", /* SIGPROF */ - "winch", /* SIGWINCH */ - "info", /* SIGINFO */ - "usr1", /* SIGUSR1 */ - "usr2" /* SIGUSR2 */ + "HUP", /* SIGHUP */ + "INT", /* SIGINT */ + "QUIT", /* SIGQUIT */ + "ILL", /* SIGILL */ + "TRAP", /* SIGTRAP */ + "ABRT", /* SIGABRT */ + "EMT", /* SIGEMT */ + "FPE", /* SIGFPE */ + "KILL", /* SIGKILL */ + "BUS", /* SIGBUS */ + "SEGV", /* SIGSEGV */ + "SYS", /* SIGSYS */ + "PIPE", /* SIGPIPE */ + "ALRM", /* SIGALRM */ + "TERM", /* SIGTERM */ + "URG", /* SIGURG */ + "STOP", /* SIGSTOP */ + "TSTP", /* SIGTSTP */ + "CONT", /* SIGCONT */ + "CHLD", /* SIGCHLD */ + "TTIN", /* SIGTTIN */ + "TTOU", /* SIGTTOU */ + "IO", /* SIGIO */ + "XCPU", /* SIGXCPU */ + "XFSZ", /* SIGXFSZ */ + "VTALRM", /* SIGVTALRM */ + "PROF", /* SIGPROF */ + "WINCH", /* SIGWINCH */ + "INFO", /* SIGINFO */ + "USR1", /* SIGUSR1 */ + "USR2" /* SIGUSR2 */ }; const char *const sys_siglist[NSIG] = { diff --git a/lib/libc/gen/stringlist.3 b/lib/libc/gen/stringlist.3 index 44d2a36..82465b6 100644 --- a/lib/libc/gen/stringlist.3 +++ b/lib/libc/gen/stringlist.3 @@ -29,8 +29,8 @@ .\" $FreeBSD$ .\" .Dd November 28, 1999 -.Os .Dt STRINGLIST 3 +.Os .Sh NAME .Nm stringlist , .Nm sl_init , @@ -66,7 +66,6 @@ typedef struct _stringlist { size_t sl_cur; } StringList; .Ed -.Pp .Bl -tag -width "sl_str" -offset indent .It Va sl_str a pointer to the base of the array containing the list. diff --git a/lib/libc/gen/sysconf.3 b/lib/libc/gen/sysconf.3 index b17d8a8..51f7eeb 100644 --- a/lib/libc/gen/sysconf.3 +++ b/lib/libc/gen/sysconf.3 @@ -28,7 +28,7 @@ .\" @(#)sysconf.3 8.3 (Berkeley) 4/19/94 .\" $FreeBSD$ .\" -.Dd December 14, 2006 +.Dd February 13, 2011 .Dt SYSCONF 3 .Os .Sh NAME @@ -60,9 +60,7 @@ Shell programmers who need access to these parameters should use the utility. .Pp The available values are as follows: -.Pp .Bl -tag -width 6n -.Pp .It Li _SC_ARG_MAX The maximum bytes of argument to .Xr execve 2 . @@ -87,6 +85,9 @@ The number of processors currently online. The maximum number of open files per user id. .It Li _SC_PAGESIZE The size of a system page in bytes. +.It Li _SC_PAGE_SIZE +Equivalent to +.Li _SC_PAGESIZE . .It Li _SC_STREAM_MAX The minimum maximum number of streams that a process may have open at any one time. @@ -162,12 +163,64 @@ otherwise \-1. .It Li _SC_2_UPE Return 1 if the system supports the User Portability Utilities Option, otherwise \-1. +.It Li _SC_AIO_LISTIO_MAX +Maximum number of I/O operations in a single list I/O call supported. +.It Li _SC_AIO_MAX +Maximum number of outstanding asynchronous I/O operations supported. +.It Li _SC_AIO_PRIO_DELTA_MAX +The maximum amount by which a process can decrease its asynchronous I/O +priority level from its own scheduling priority. +.It Li _SC_DELAYTIMER_MAX +Maximum number of timer expiration overruns. +.It Li _SC_MQ_OPEN_MAX +The maximum number of open message queue descriptors a process may hold. +.It Li _SC_RTSIG_MAX +Maximum number of realtime signals reserved for application use. +.It Li _SC_SEM_NSEMS_MAX +Maximum number of semaphores that a process may have. +.It Li _SC_SEM_VALUE_MAX +The maximum value a semaphore may have. +.It Li _SC_SIGQUEUE_MAX +Maximum number of queued signals that a process may send and have pending at +the receiver(s) at any time. +.It Li _SC_TIMER_MAX +Maximum number of timers per process supported. +.It Li _SC_GETGR_R_SIZE_MAX +Suggested initial value for the size of the group entry buffer. +.It Li _SC_GETPW_R_SIZE_MAX +Suggested initial value for the size of the password entry buffer. +.It Li _SC_HOST_NAME_MAX +Maximum length of a host name (not including the terminating null) as +returned from the +.Fn gethostname +function. +.It Li _SC_LOGIN_NAME_MAX +Maximum length of a login name. +.It Li _SC_THREAD_STACK_MIN +Minimum size in bytes of thread stack storage. +.It Li _SC_THREAD_THREADS_MAX +Maximum number of threads that can be created per process. +.It Li _SC_TTY_NAME_MAX +Maximum length of terminal device name. +.It Li _SC_SYMLOOP_MAX +Maximum number of symbolic links that can be reliably traversed in the +resolution of a pathname in the absence of a loop. +.It Li _SC_ATEXIT_MAX +Maximum number of functions that may be registered with +.Fn atexit . +.It Li _SC_XOPEN_VERSION +An integer value greater than or equal to 4, +indicating the version of the X/Open Portability Guide to which this +system conforms. +.It Li _SC_XOPEN_XCU_VERSION +An integer value indicating the version of the XCU Specification to which +this system conforms. .El .Pp These values also exist, but may not be standard: -.Pp .Bl -tag -width 6n -.Pp +.It Li _SC_CPUSET_SIZE +Size of the kernel cpuset. .It Li _SC_PHYS_PAGES The number of pages of physical memory. Note that it is possible that the product of this value and the value of diff --git a/lib/libc/gen/sysconf.c b/lib/libc/gen/sysconf.c index 4618f32..7539d61 100644 --- a/lib/libc/gen/sysconf.c +++ b/lib/libc/gen/sysconf.c @@ -597,6 +597,15 @@ yesno: return (lvalue); #endif +#ifdef _SC_CPUSET_SIZE + case _SC_CPUSET_SIZE: + len = sizeof(lvalue); + if (sysctlbyname("kern.sched.cpusetsize", &lvalue, &len, NULL, + 0) == -1) + return (-1); + return (lvalue); +#endif + default: errno = EINVAL; return (-1); diff --git a/lib/libc/gen/sysctl.3 b/lib/libc/gen/sysctl.3 index 143be16..a841545 100644 --- a/lib/libc/gen/sysctl.3 +++ b/lib/libc/gen/sysctl.3 @@ -28,7 +28,7 @@ .\" @(#)sysctl.3 8.4 (Berkeley) 5/9/95 .\" $FreeBSD$ .\" -.Dd February 21, 2010 +.Dd April 25, 2010 .Dt SYSCTL 3 .Os .Sh NAME @@ -183,7 +183,6 @@ The top level names are defined with a CTL_ prefix in and are as follows. The next and subsequent levels down are found in the include files listed here, and described in separate sections below. -.Pp .Bl -column CTLXMACHDEPXXX "Next level namesXXXXXX" -offset indent .It Sy "Name Next level names Description" .It "CTL_DEBUG sys/sysctl.h Debugging" @@ -286,7 +285,6 @@ privilege may change the value. .It "HW_MACHINE_ARCH string no" .It "HW_REALMEM integer no" .El -.Pp .Bl -tag -width 6n .It Li HW_MACHINE The machine class. @@ -326,7 +324,7 @@ information. .It "KERN_BOOTFILE string yes" .It "KERN_BOOTTIME struct timeval no" .It "KERN_CLOCKRATE struct clockinfo no" -.It "KERN_FILE struct file no" +.It "KERN_FILE struct xfile no" .It "KERN_HOSTID integer yes" .It "KERN_HOSTUUID string yes" .It "KERN_HOSTNAME string yes" @@ -343,16 +341,15 @@ information. .It "KERN_OSREV integer no" .It "KERN_OSTYPE string no" .It "KERN_POSIX1 integer no" -.It "KERN_PROC struct proc no" +.It "KERN_PROC node not applicable" .It "KERN_PROF node not applicable" .It "KERN_QUANTUM integer yes" .It "KERN_SAVED_IDS integer no" .It "KERN_SECURELVL integer raise only" .It "KERN_UPDATEINTERVAL integer no" .It "KERN_VERSION string no" -.It "KERN_VNODE struct vnode no" +.It "KERN_VNODE struct xvnode no" .El -.Pp .Bl -tag -width 6n .It Li KERN_ARGMAX The maximum bytes of argument to @@ -372,10 +369,8 @@ This structure contains the clock, statistics clock and profiling clock frequencies, the number of micro-seconds per hz tick and the skew rate. .It Li KERN_FILE Return the entire file table. -The returned data consists of a single -.Va struct filehead -followed by an array of -.Va struct file , +The returned data consists of an array of +.Va struct xfile , whose size depends on the current number of such objects in the system. .It Li KERN_HOSTID Get or set the host ID. @@ -527,10 +522,8 @@ Note, the vnode table is not necessarily a consistent snapshot of the system. The returned data consists of an array whose size depends on the current number of such objects in the system. -Each element of the array contains the kernel address of a vnode -.Va struct vnode * -followed by the vnode itself -.Va struct vnode . +Each element of the array consists of a +.Va struct xvnode . .El .Ss CTL_NET The string and integer information available for the CTL_NET level @@ -543,7 +536,6 @@ privilege may change the value. .It "PF_INET IPv4 values yes" .It "PF_INET6 IPv6 values yes" .El -.Pp .Bl -tag -width 6n .It Li PF_ROUTE Return the entire routing table or a subset of it. @@ -650,7 +642,6 @@ privilege may change the value. .It "USER_TZNAME_MAX integer no" .El .Bl -tag -width 6n -.Pp .It Li USER_BC_BASE_MAX The maximum ibase/obase values in the .Xr bc 1 @@ -740,7 +731,6 @@ privilege may change the value. .It "VM_V_INACTIVE_TARGET integer yes" .It "VM_V_PAGEOUT_FREE_MIN integer yes" .El -.Pp .Bl -tag -width 6n .It Li VM_LOADAVG Return the load average history. @@ -859,6 +849,8 @@ An attempt is made to set a read-only value. A process without appropriate privilege attempts to set a value. .El .Sh SEE ALSO +.Xr confstr 3 , +.Xr kvm 3 , .Xr sysconf 3 , .Xr sysctl 8 .Sh HISTORY diff --git a/lib/libc/gen/syslog.c b/lib/libc/gen/syslog.c index 594fb97..6f04703 100644 --- a/lib/libc/gen/syslog.c +++ b/lib/libc/gen/syslog.c @@ -342,7 +342,7 @@ connectlog(void) if (LogFile == -1) { if ((LogFile = _socket(AF_UNIX, SOCK_DGRAM, 0)) == -1) return; - (void)_fcntl(LogFile, F_SETFD, 1); + (void)_fcntl(LogFile, F_SETFD, FD_CLOEXEC); } if (LogFile != -1 && status == NOCONN) { SyslogAddr.sun_len = sizeof(SyslogAddr); diff --git a/lib/libc/gen/tcgetsid.3 b/lib/libc/gen/tcgetsid.3 index a270a0b..60bff8d 100644 --- a/lib/libc/gen/tcgetsid.3 +++ b/lib/libc/gen/tcgetsid.3 @@ -1,4 +1,4 @@ -.\" Copyright (c) 2008 David Xu <davidxu@freebsd.org> +.\" Copyright (c) 2008 David Xu <davidxu@FreeBSD.org> .\" All rights reserved. .\" .\" Redistribution and use in source and binary forms, with or without diff --git a/lib/libc/gen/tcsetattr.3 b/lib/libc/gen/tcsetattr.3 index 01628d3..9be012e 100644 --- a/lib/libc/gen/tcsetattr.3 +++ b/lib/libc/gen/tcsetattr.3 @@ -38,6 +38,7 @@ .Nm cfsetospeed , .Nm cfsetspeed , .Nm cfmakeraw , +.Nm cfmakesane , .Nm tcgetattr , .Nm tcsetattr .Nd manipulating the termios structure @@ -57,6 +58,8 @@ .Fn cfsetspeed "struct termios *t" "speed_t speed" .Ft void .Fn cfmakeraw "struct termios *t" +.Ft void +.Fn cfmakesane "struct termios *t" .Ft int .Fn tcgetattr "int fd" "struct termios *t" .Ft int @@ -64,6 +67,7 @@ .Sh DESCRIPTION The .Fn cfmakeraw , +.Fn cfmakesane , .Fn tcgetattr and .Fn tcsetattr @@ -180,14 +184,20 @@ The .Fn cfmakeraw function sets the flags stored in the termios structure to a state disabling all input and output processing, giving a -.Dq raw I/O path . +.Dq raw I/O path , +while the +.Fn cfmakesane +function sets them to a state similar to those of a newly created +terminal device. 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 .Fn tcgetattr , -setting raw mode with +setting raw or sane mode with .Fn cfmakeraw +or +.Fn cfmakesane and the subsequent .Fn tcsetattr , and then using another @@ -316,7 +326,8 @@ functions are expected to be compliant with the .St -p1003.1-88 specification. The -.Fn cfmakeraw +.Fn cfmakeraw , +.Fn cfmakesane and .Fn cfsetspeed functions, diff --git a/lib/libc/gen/termios.c b/lib/libc/gen/termios.c index fc21757..7e9f169 100644 --- a/lib/libc/gen/termios.c +++ b/lib/libc/gen/termios.c @@ -40,6 +40,8 @@ __FBSDID("$FreeBSD$"); #include <sys/time.h> #include <errno.h> +#include <string.h> +#define TTYDEFCHARS #include <termios.h> #include <unistd.h> #include "un-namespace.h" @@ -173,6 +175,23 @@ cfmakeraw(struct termios *t) t->c_cc[VTIME] = 0; } +/* + * Obtain a termios structure which is similar to the one provided by + * the kernel. + */ +void +cfmakesane(struct termios *t) +{ + + t->c_cflag = TTYDEF_CFLAG; + t->c_iflag = TTYDEF_IFLAG; + t->c_lflag = TTYDEF_LFLAG; + t->c_oflag = TTYDEF_OFLAG; + t->c_ispeed = TTYDEF_SPEED; + t->c_ospeed = TTYDEF_SPEED; + memcpy(&t->c_cc, ttydefchars, sizeof ttydefchars); +} + int tcsendbreak(int fd, int len __unused) { diff --git a/lib/libc/gen/ualarm.3 b/lib/libc/gen/ualarm.3 index 47575cf..5719896 100644 --- a/lib/libc/gen/ualarm.3 +++ b/lib/libc/gen/ualarm.3 @@ -84,8 +84,8 @@ A microsecond is 0.000001 seconds. .Sh SEE ALSO .Xr getitimer 2 , .Xr setitimer 2 , -.Xr sigpause 2 , -.Xr sigvec 2 , +.Xr sigaction 2 , +.Xr sigsuspend 2 , .Xr alarm 3 , .Xr signal 3 , .Xr sleep 3 , diff --git a/lib/libc/gen/utxdb.c b/lib/libc/gen/utxdb.c index 6a85c05..743629d 100644 --- a/lib/libc/gen/utxdb.c +++ b/lib/libc/gen/utxdb.c @@ -132,9 +132,8 @@ futx_to_utx(const struct futx *fu) ut = calloc(1, sizeof *ut); if (ut == NULL) return (NULL); - } else { + } else memset(ut, 0, sizeof *ut); - } switch (fu->fu_type) { case BOOT_TIME: diff --git a/lib/libc/gmon/gmon.c b/lib/libc/gmon/gmon.c index fe769e8..edf4e2f 100644 --- a/lib/libc/gmon/gmon.c +++ b/lib/libc/gmon/gmon.c @@ -41,6 +41,7 @@ __FBSDID("$FreeBSD$"); #include <err.h> #include <fcntl.h> +#include <inttypes.h> #include <stdio.h> #include <stdlib.h> #include <string.h> @@ -49,8 +50,10 @@ __FBSDID("$FreeBSD$"); #include "libc_private.h" -#if defined(__i386__) || defined(__sparc64__) || defined(__amd64__) || defined(__powerpc__) +#if defined(__i386__) || defined(__sparc64__) || defined(__amd64__) || (defined(__powerpc__) && !defined(__powerpc64__)) extern char *minbrk __asm (".minbrk"); +#elif defined(__powerpc64__) +extern char *minbrk __asm ("_minbrk"); #else extern char *minbrk __asm ("minbrk"); #endif @@ -58,8 +61,8 @@ extern char *minbrk __asm ("minbrk"); struct gmonparam _gmonparam = { GMON_PROF_OFF }; static int s_scale; -/* see profil(2) where this is describe (incorrectly) */ -#define SCALE_1_TO_1 0x10000L +/* See profil(2) where this is described (incorrectly). */ +#define SCALE_SHIFT 16 #define ERR(s) _write(2, s, sizeof(s)) @@ -110,24 +113,8 @@ monstartup(lowpc, highpc) p->tos[0].link = 0; o = p->highpc - p->lowpc; - if (p->kcountsize < o) { -#ifndef hp300 - s_scale = ((float)p->kcountsize / o ) * SCALE_1_TO_1; -#else /* avoid floating point */ - int 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; - + s_scale = (p->kcountsize < o) ? + ((uintmax_t)p->kcountsize << SCALE_SHIFT) / o : (1 << SCALE_SHIFT); moncontrol(1); } diff --git a/lib/libc/i386/gen/_ctx_start.S b/lib/libc/i386/gen/_ctx_start.S index 7083d3c..fdea371 100644 --- a/lib/libc/i386/gen/_ctx_start.S +++ b/lib/libc/i386/gen/_ctx_start.S @@ -50,3 +50,5 @@ ENTRY(_ctx_start) call PIC_PLT(abort) /* fubar */ ret END(_ctx_start) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/gen/_setjmp.S b/lib/libc/i386/gen/_setjmp.S index 7eb1ae3..3d9fdb4 100644 --- a/lib/libc/i386/gen/_setjmp.S +++ b/lib/libc/i386/gen/_setjmp.S @@ -78,3 +78,5 @@ ENTRY(___longjmp) 1: movl %ecx,0(%esp) ret END(___longjmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/gen/fabs.S b/lib/libc/i386/gen/fabs.S index 9903fd3..7fb1531 100644 --- a/lib/libc/i386/gen/fabs.S +++ b/lib/libc/i386/gen/fabs.S @@ -41,3 +41,5 @@ ENTRY(fabs) fabs ret END(fabs) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/gen/modf.S b/lib/libc/i386/gen/modf.S index 0f7112e..33c211f 100644 --- a/lib/libc/i386/gen/modf.S +++ b/lib/libc/i386/gen/modf.S @@ -83,3 +83,5 @@ ENTRY(modf) leave ret END(modf) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/gen/rfork_thread.S b/lib/libc/i386/gen/rfork_thread.S index 841717a..3333d84 100644 --- a/lib/libc/i386/gen/rfork_thread.S +++ b/lib/libc/i386/gen/rfork_thread.S @@ -116,3 +116,5 @@ ENTRY(rfork_thread) PIC_PROLOGUE jmp PIC_PLT(HIDENAME(cerror)) END(rfork_thread) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/gen/setjmp.S b/lib/libc/i386/gen/setjmp.S index 6f6cd89..5d0ddc4 100644 --- a/lib/libc/i386/gen/setjmp.S +++ b/lib/libc/i386/gen/setjmp.S @@ -98,3 +98,5 @@ ENTRY(__longjmp) 1: movl %ecx,0(%esp) ret END(__longjmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/gen/sigsetjmp.S b/lib/libc/i386/gen/sigsetjmp.S index 6134d03..6487745 100644 --- a/lib/libc/i386/gen/sigsetjmp.S +++ b/lib/libc/i386/gen/sigsetjmp.S @@ -110,3 +110,5 @@ ENTRY(__siglongjmp) 1: movl %ecx,0(%esp) ret END(__siglongjmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/stdlib/div.S b/lib/libc/i386/stdlib/div.S index 42e7ef4..81d6e6e 100644 --- a/lib/libc/i386/stdlib/div.S +++ b/lib/libc/i386/stdlib/div.S @@ -35,3 +35,5 @@ ENTRY(div) idiv %ecx ret END(div) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/stdlib/ldiv.S b/lib/libc/i386/stdlib/ldiv.S index b0455bf..c40c631 100644 --- a/lib/libc/i386/stdlib/ldiv.S +++ b/lib/libc/i386/stdlib/ldiv.S @@ -38,3 +38,5 @@ ENTRY(ldiv) idiv %ecx ret END(ldiv) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/Makefile.inc b/lib/libc/i386/string/Makefile.inc index cd908a6..3292267 100644 --- a/lib/libc/i386/string/Makefile.inc +++ b/lib/libc/i386/string/Makefile.inc @@ -3,5 +3,5 @@ MDSRCS+=bcmp.S bcopy.S bzero.S ffs.S index.S memchr.S memcmp.S memcpy.S \ memmove.S memset.S rindex.S strcat.S strchr.S strcmp.S strcpy.S \ - strlen.S strncmp.S strrchr.S swab.S wcschr.S wcscmp.S wcslen.S \ + strncmp.S strrchr.S swab.S wcschr.S wcscmp.S wcslen.S \ wmemchr.S diff --git a/lib/libc/i386/string/bcmp.S b/lib/libc/i386/string/bcmp.S index eaf9666..b25ee6e 100644 --- a/lib/libc/i386/string/bcmp.S +++ b/lib/libc/i386/string/bcmp.S @@ -62,3 +62,5 @@ L1: popl %edi ret END(bcmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/bcopy.S b/lib/libc/i386/string/bcopy.S index 2f3525e..cab1de6 100644 --- a/lib/libc/i386/string/bcopy.S +++ b/lib/libc/i386/string/bcopy.S @@ -106,3 +106,5 @@ END(memmove) END(bcopy) #endif #endif + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/bzero.S b/lib/libc/i386/string/bzero.S index 3c22b36..c8d3776 100644 --- a/lib/libc/i386/string/bzero.S +++ b/lib/libc/i386/string/bzero.S @@ -80,3 +80,5 @@ L1: rep popl %edi ret END(bzero) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/ffs.S b/lib/libc/i386/string/ffs.S index e668447..3a0431c 100644 --- a/lib/libc/i386/string/ffs.S +++ b/lib/libc/i386/string/ffs.S @@ -52,3 +52,5 @@ ENTRY(ffs) L1: xorl %eax,%eax /* clear result */ ret END(ffs) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/index.S b/lib/libc/i386/string/index.S index e7e7a8c..3bdd68d 100644 --- a/lib/libc/i386/string/index.S +++ b/lib/libc/i386/string/index.S @@ -62,3 +62,5 @@ L2: popl %ebx ret END(index) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/memchr.S b/lib/libc/i386/string/memchr.S index a313d4d..03828db 100644 --- a/lib/libc/i386/string/memchr.S +++ b/lib/libc/i386/string/memchr.S @@ -57,3 +57,5 @@ L1: xorl %eax,%eax popl %edi ret END(memchr) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/memcmp.S b/lib/libc/i386/string/memcmp.S index fa9586f..cbb3b8a 100644 --- a/lib/libc/i386/string/memcmp.S +++ b/lib/libc/i386/string/memcmp.S @@ -74,3 +74,5 @@ L6: movzbl -1(%edi),%eax /* Perform unsigned comparison */ popl %edi ret END(memcmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/memset.S b/lib/libc/i386/string/memset.S index 25768c22..f5da603 100644 --- a/lib/libc/i386/string/memset.S +++ b/lib/libc/i386/string/memset.S @@ -88,3 +88,5 @@ L1: rep popl %edi ret END(memset) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/rindex.S b/lib/libc/i386/string/rindex.S index c52f6d3..e59406c9 100644 --- a/lib/libc/i386/string/rindex.S +++ b/lib/libc/i386/string/rindex.S @@ -63,3 +63,5 @@ L2: popl %ebx ret END(rindex) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/strcat.S b/lib/libc/i386/string/strcat.S index 6715bd8..835a7e9 100644 --- a/lib/libc/i386/string/strcat.S +++ b/lib/libc/i386/string/strcat.S @@ -99,3 +99,5 @@ L2: popl %eax /* pop destination address */ popl %edi /* restore edi */ ret END(strcat) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/strchr.S b/lib/libc/i386/string/strchr.S index 8c518fb..ddae795 100644 --- a/lib/libc/i386/string/strchr.S +++ b/lib/libc/i386/string/strchr.S @@ -62,3 +62,5 @@ L2: popl %ebx ret END(strchr) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/strcmp.S b/lib/libc/i386/string/strcmp.S index 9ca104e..6599577 100644 --- a/lib/libc/i386/string/strcmp.S +++ b/lib/libc/i386/string/strcmp.S @@ -118,3 +118,5 @@ L3: movzbl (%eax),%eax /* unsigned comparison */ subl %edx,%eax ret END(strcmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/strcpy.S b/lib/libc/i386/string/strcpy.S index 7367c07..c5113f6 100644 --- a/lib/libc/i386/string/strcpy.S +++ b/lib/libc/i386/string/strcpy.S @@ -88,3 +88,5 @@ L1: movb (%edx),%al /* unroll loop, but not too much */ L2: popl %eax /* pop dst address */ ret END(strcpy) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/strncmp.S b/lib/libc/i386/string/strncmp.S index 98e3656..ec9b531 100644 --- a/lib/libc/i386/string/strncmp.S +++ b/lib/libc/i386/string/strncmp.S @@ -165,3 +165,5 @@ L4: xorl %eax,%eax popl %ebx ret END(strncmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/strrchr.S b/lib/libc/i386/string/strrchr.S index f044c2e..0d7f0ca 100644 --- a/lib/libc/i386/string/strrchr.S +++ b/lib/libc/i386/string/strrchr.S @@ -63,3 +63,5 @@ L2: popl %ebx ret END(strrchr) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/swab.S b/lib/libc/i386/string/swab.S index 5035de2..3d21e64 100644 --- a/lib/libc/i386/string/swab.S +++ b/lib/libc/i386/string/swab.S @@ -98,3 +98,5 @@ L4: popl %edi popl %esi ret END(swab) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/wcschr.S b/lib/libc/i386/string/wcschr.S index 8f6c543..37862a9 100644 --- a/lib/libc/i386/string/wcschr.S +++ b/lib/libc/i386/string/wcschr.S @@ -75,3 +75,5 @@ no: popl %ebx xorl %eax,%eax ret END(wcschr) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/wcscmp.S b/lib/libc/i386/string/wcscmp.S index 8d0700a..6fbcb8c 100644 --- a/lib/libc/i386/string/wcscmp.S +++ b/lib/libc/i386/string/wcscmp.S @@ -78,3 +78,5 @@ no0: subl (%esi),%eax popl %edi ret END(wcscmp) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/wcslen.S b/lib/libc/i386/string/wcslen.S index 9fea2b0..691e17f 100644 --- a/lib/libc/i386/string/wcslen.S +++ b/lib/libc/i386/string/wcslen.S @@ -67,3 +67,5 @@ found1: incl %eax found0: popl %ebx ret END(wcslen) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/wmemchr.S b/lib/libc/i386/string/wmemchr.S index 2b5270b..2e81c09 100644 --- a/lib/libc/i386/string/wmemchr.S +++ b/lib/libc/i386/string/wmemchr.S @@ -104,3 +104,5 @@ no: xorl %eax,%eax popl %edi ret END(wmemchr) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/Ovfork.S b/lib/libc/i386/sys/Ovfork.S index 25a9d94..e3cc45d 100644 --- a/lib/libc/i386/sys/Ovfork.S +++ b/lib/libc/i386/sys/Ovfork.S @@ -53,3 +53,5 @@ ENTRY(__sys_vfork) PIC_PROLOGUE jmp PIC_PLT(HIDENAME(cerror)) END(__sys_vfork) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/brk.S b/lib/libc/i386/sys/brk.S index f67a2a2..968e437 100644 --- a/lib/libc/i386/sys/brk.S +++ b/lib/libc/i386/sys/brk.S @@ -86,3 +86,5 @@ err: jmp HIDENAME(cerror) #endif END(brk) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/cerror.S b/lib/libc/i386/sys/cerror.S index 3e8d539..129cc1b 100644 --- a/lib/libc/i386/sys/cerror.S +++ b/lib/libc/i386/sys/cerror.S @@ -63,3 +63,4 @@ HIDENAME(cerror): movl $-1,%edx ret + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/exect.S b/lib/libc/i386/sys/exect.S index 5eb0d44..3ae87b8 100644 --- a/lib/libc/i386/sys/exect.S +++ b/lib/libc/i386/sys/exect.S @@ -50,3 +50,5 @@ ENTRY(exect) PIC_PROLOGUE jmp PIC_PLT(HIDENAME(cerror)) /* exect(file, argv, env); */ END(exect) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/getcontext.S b/lib/libc/i386/sys/getcontext.S index 6942749..c24dbdc 100644 --- a/lib/libc/i386/sys/getcontext.S +++ b/lib/libc/i386/sys/getcontext.S @@ -49,3 +49,5 @@ ENTRY(__sys_getcontext) PIC_PROLOGUE jmp PIC_PLT(HIDENAME(cerror)) END(__sys_getcontext) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/pipe.S b/lib/libc/i386/sys/pipe.S index 0ce3a8c..85f4fd2 100644 --- a/lib/libc/i386/sys/pipe.S +++ b/lib/libc/i386/sys/pipe.S @@ -45,3 +45,5 @@ SYSCALL(pipe) movl $0,%eax ret END(__sys_pipe) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/ptrace.S b/lib/libc/i386/sys/ptrace.S index 7527e7e..6e5e885 100644 --- a/lib/libc/i386/sys/ptrace.S +++ b/lib/libc/i386/sys/ptrace.S @@ -56,3 +56,5 @@ err: PIC_PROLOGUE jmp PIC_PLT(HIDENAME(cerror)) END(ptrace) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/reboot.S b/lib/libc/i386/sys/reboot.S index d5caccf..f11000e 100644 --- a/lib/libc/i386/sys/reboot.S +++ b/lib/libc/i386/sys/reboot.S @@ -41,3 +41,5 @@ __FBSDID("$FreeBSD$"); SYSCALL(reboot) iret END(__sys_reboot) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/sbrk.S b/lib/libc/i386/sys/sbrk.S index 36a1b55..337087a 100644 --- a/lib/libc/i386/sys/sbrk.S +++ b/lib/libc/i386/sys/sbrk.S @@ -89,3 +89,5 @@ err: jmp HIDENAME(cerror) #endif /* PIC */ END(sbrk) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/setlogin.S b/lib/libc/i386/sys/setlogin.S index 2a814bd..c6436b5 100644 --- a/lib/libc/i386/sys/setlogin.S +++ b/lib/libc/i386/sys/setlogin.S @@ -53,3 +53,5 @@ SYSCALL(setlogin) #endif ret /* setlogin(name) */ END(__sys_setlogin) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/sigreturn.S b/lib/libc/i386/sys/sigreturn.S index 28dc227..f91816e 100644 --- a/lib/libc/i386/sys/sigreturn.S +++ b/lib/libc/i386/sys/sigreturn.S @@ -44,3 +44,5 @@ __FBSDID("$FreeBSD$"); */ RSYSCALL(sigreturn) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/sys/syscall.S b/lib/libc/i386/sys/syscall.S index d26ce47..e5d6e23 100644 --- a/lib/libc/i386/sys/syscall.S +++ b/lib/libc/i386/sys/syscall.S @@ -51,3 +51,5 @@ ENTRY(syscall) PIC_PROLOGUE jmp PIC_PLT(HIDENAME(cerror)) END(syscall) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/ia64/gen/modf.c b/lib/libc/ia64/gen/modf.c index def3aad..13e6182 100644 --- a/lib/libc/ia64/gen/modf.c +++ b/lib/libc/ia64/gen/modf.c @@ -85,7 +85,7 @@ modf(val, iptr) * 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 the fractional part is the part with the rest of the + * 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 diff --git a/lib/libc/iconv/Makefile.inc b/lib/libc/iconv/Makefile.inc new file mode 100644 index 0000000..8c43a20 --- /dev/null +++ b/lib/libc/iconv/Makefile.inc @@ -0,0 +1,18 @@ +# $FreeBSD$ + +# iconv sources +.PATH: ${.CURDIR}/iconv + +MAN+= iconv.3 iconvctl.3 iconv_canonicalize.3 iconvlist.3 __iconv_get_list.3 +MLINKS+= iconv.3 iconv_open.3 \ + iconv.3 iconv_open_into.3 \ + iconv.3 iconv_close.3 \ + iconv.3 __iconv.3 \ + __iconv_get_list.3 __iconv_free_list.3 +SRCS+= citrus_bcs.c citrus_bcs_strtol.c citrus_bcs_strtoul.c \ + citrus_csmapper.c citrus_db.c citrus_db_factory.c citrus_db_hash.c \ + citrus_esdb.c citrus_hash.c citrus_iconv.c citrus_lookup.c \ + citrus_lookup_factory.c citrus_mapper.c citrus_memstream.c \ + citrus_mmap.c citrus_module.c citrus_none.c citrus_pivot_factory.c \ + citrus_prop.c citrus_stdenc.c iconv.c +SYM_MAPS+= ${.CURDIR}/iconv/Symbol.map diff --git a/lib/libc/iconv/Symbol.map b/lib/libc/iconv/Symbol.map new file mode 100644 index 0000000..73e0e22 --- /dev/null +++ b/lib/libc/iconv/Symbol.map @@ -0,0 +1,104 @@ +/* + * $FreeBSD$ + */ + +FBSD_1.2 { + __iconv; + __iconv_free_list; + __iconv_get_list; + _libiconv_version; + iconv_canonicalize; + libiconv; + libiconv_close; + libiconv_open; + libiconv_open_into; + libiconv_set_relocation_prefix; + libiconvctl; + libiconvlist; +}; + +FBSDprivate_1.0 { + _citrus_bcs_convert_to_lower; + _citrus_bcs_convert_to_upper; + _citrus_bcs_isalnum; + _citrus_bcs_isalpha; + _citrus_bcs_isblank; + _citrus_bcs_isdigit; + _citrus_bcs_iseol; + _citrus_bcs_islower; + _citrus_bcs_isspace; + _citrus_bcs_isupper; + _citrus_bcs_isxdigit; + _citrus_bcs_skip_nonws; + _citrus_bcs_skip_nonws_len; + _citrus_bcs_skip_ws; + _citrus_bcs_skip_ws_len; + _citrus_bcs_strcasecmp; + _citrus_bcs_strncasecmp; + _citrus_bcs_strtol; + _citrus_bcs_strtoul; + _citrus_bcs_tolower; + _citrus_bcs_toupper; + _citrus_bcs_trunc_ws_len; + _citrus_csmapper_open; + _citrus_csmapper_close; + _citrus_db_factory_add_by_string; + _citrus_db_factory_add_string_by_string; + _citrus_db_factory_add32_by_string; + _citrus_db_factory_calc_size; + _citrus_db_factory_create; + _citrus_db_factory_serialize; + _citrus_db_hash_std; + _citrus_db_close; + _citrus_db_get_entry; + _citrus_db_get_number_of_entries; + _citrus_db_lookup; + _citrus_db_lookup_by_string; + _citrus_db_lookup8_by_string; + _citrus_db_lookup16_by_string; + _citrus_db_lookup_string_by_string; + _citrus_db_open; + _citrus_esdb_close; + _citrus_esdb_open; + _citrus_lookup_factory_convert; + _citrus_map_file; + _citrus_mapper_close; + _citrus_mapper_convert; + _citrus_mapper_create_area; + _citrus_mapper_get_dst_max; + _citrus_mapper_get_src_max; + _citrus_mapper_get_state_size; + _citrus_mapper_init_state; + _citrus_mapper_open; + _citrus_mapper_open_direct; + _citrus_mapper_set_persistent; + _citrus_memory_stream_bind; + _citrus_memory_stream_chr; + _citrus_memory_stream_getc; + _citrus_memory_stream_getln; + _citrus_memory_stream_getln_region; + _citrus_memory_stream_getregion; + _citrus_memory_stream_iseof; + _citrus_memory_stream_matchline; + _citrus_memory_stream_peek; + _citrus_memory_stream_remainder; + _citrus_memory_stream_rewind; + _citrus_memory_stream_seek; + _citrus_memory_stream_skip_ws; + _citrus_memory_stream_tell; + _citrus_memory_stream_ungetc; + _citrus_pivot_factory_convert; + _citrus_prop_object_init; + _citrus_prop_object_uninit; + _citrus_prop_parse_variable; + _citrus_prop_read_bool; + _citrus_prop_read_character; + _citrus_prop_read_character_common; + _citrus_prop_read_element; + _citrus_prop_read_num; + _citrus_prop_read_str; + _citrus_prop_read_symbol; + _citrus_stdenc_close; + _citrus_stdenc_open; + _citrus_unmap_file; +}; diff --git a/lib/libc/iconv/__iconv_get_list.3 b/lib/libc/iconv/__iconv_get_list.3 new file mode 100644 index 0000000..7c8d015 --- /dev/null +++ b/lib/libc/iconv/__iconv_get_list.3 @@ -0,0 +1,95 @@ +.\" Copyright (c) 2009 Gabor Kovesdan <gabor@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. +.\" +.\" Portions of this text are reprinted and reproduced in electronic form +.\" from IEEE Std 1003.1, 2004 Edition, Standard for Information Technology -- +.\" Portable Operating System Interface (POSIX), The Open Group Base +.\" Specifications Issue 6, Copyright (C) 2001-2004 by the Institute of +.\" Electrical and Electronics Engineers, Inc and The Open Group. In the +.\" event of any discrepancy between this version and the original IEEE and +.\" The Open Group Standard, the original IEEE and The Open Group Standard is +.\" the referee document. The original Standard can be obtained online at +.\" http://www.opengroup.org/unix/online.html. +.\" +.\" $FreeBSD$ +.\" +.Dd October 20, 2009 +.Dt __ICONV_GET_LIST 3 +.Os +.Sh NAME +.Nm __iconv_get_list +.Nm __iconv_free_list +.Nd retrieving a list of character encodings supported by +.Xr iconv 3 +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In iconv.h +.Ft int +.Fn __iconv_get_list "char ***names" "size_t count" "bool paired" +.Ft void +.Fn __iconv_free_list "char **names" "size_t count" +.Sh DESCRIPTION +The +.Fn __iconv_get_list +function obtains a list of character encodings that are supported by the +.Xr iconv 3 +call. +The list of the encoding names will be stored in +.Fa names +and the number of the entries is stored in +.Fa count . +If the +.Fa paired +variable is true, the list will be arranged into +canonical/alias name pairs. +.Pp +The +.Fn __iconv_free_list +function is to free the allocated memory during the call of +.Fn __iconv_get_list . +.Sh RETURN VALUES +Upon successful completion +.Fn __iconv_get_list +returns 0 and set the +.Fa names +and +.Fa count +arguments. +Otherwise, \-1 is returned and errno is set to indicate the error. +.Sh SEE ALSO +.Xr iconv 3 , +.Xr iconvlist 3 +.Sh STANDARDS +The +.Nm __iconv_get_list +and +.Nm __iconv_free_list +functions are non-standard interfaces, which appeared in +the implementation of the Citrus Project. +The iconv implementation of the Citrus Project was adopted in +.Fx 9 . +.Sh AUTHORS +This manual page was written by +.An Gabor Kovesdan Aq gabor@FreeBSD.org . diff --git a/lib/libc/iconv/_strtol.h b/lib/libc/iconv/_strtol.h new file mode 100644 index 0000000..d2d9d84 --- /dev/null +++ b/lib/libc/iconv/_strtol.h @@ -0,0 +1,167 @@ +/* $FreeBSD$ */ +/* $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 any, cutlim, i, neg; + + /* check base value */ + if (base && (base < 2 || base > 36)) { +#if !defined(_KERNEL) && !defined(_STANDALONE) + errno = EINVAL; + if (endptr != NULL) + /* LINTED interface specification */ + *endptr = __DECONST(void *, 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 = __DECONST(void *, any ? s - 1 : nptr); + return(acc); +} diff --git a/lib/libc/iconv/_strtoul.h b/lib/libc/iconv/_strtoul.h new file mode 100644 index 0000000..64e0d46 --- /dev/null +++ b/lib/libc/iconv/_strtoul.h @@ -0,0 +1,126 @@ +/* $FreeBSD$ */ +/* $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 any, cutlim, i, neg; + + /* 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 = __DECONST(void *, any ? s - 1 : nptr); + return (acc); +} diff --git a/lib/libc/iconv/citrus_aliasname_local.h b/lib/libc/iconv/citrus_aliasname_local.h new file mode 100644 index 0000000..687362b --- /dev/null +++ b/lib/libc/iconv/citrus_aliasname_local.h @@ -0,0 +1,49 @@ +/* $FreeBSD$ */ +/* $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) +{ + + return (_bcs_strcasecmp("/force", name)); +} + +#endif /*_CITRUS_ALIASNAME_LOCAL_H_*/ diff --git a/lib/libc/iconv/citrus_bcs.c b/lib/libc/iconv/citrus_bcs.c new file mode 100644 index 0000000..e86fb37 --- /dev/null +++ b/lib/libc/iconv/citrus_bcs.c @@ -0,0 +1,168 @@ +/* $FreeBSD$ */ +/* $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. + */ + +#include <sys/cdefs.h> + +#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, c2; + + c1 = 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, c2; + + c1 = 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/libc/iconv/citrus_bcs.h b/lib/libc/iconv/citrus_bcs.h new file mode 100644 index 0000000..3b1f537 --- /dev/null +++ b/lib/libc/iconv/citrus_bcs.h @@ -0,0 +1,102 @@ +/* $FreeBSD$ */ +/* $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. + */ + +#include <sys/types.h> + +#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 _citrus_bcs_strtoul(const char * __restrict, + char ** __restrict, int); +__END_DECLS + +#endif diff --git a/lib/libc/iconv/citrus_bcs_strtol.c b/lib/libc/iconv/citrus_bcs_strtol.c new file mode 100644 index 0000000..4073622 --- /dev/null +++ b/lib/libc/iconv/citrus_bcs_strtol.c @@ -0,0 +1,57 @@ +/* $FreeBSD$ */ +/* $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> + +#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 + +#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/libc/iconv/citrus_bcs_strtoul.c b/lib/libc/iconv/citrus_bcs_strtoul.c new file mode 100644 index 0000000..d9fa97c --- /dev/null +++ b/lib/libc/iconv/citrus_bcs_strtoul.c @@ -0,0 +1,57 @@ +/* $FreeBSD$ */ +/* $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. + */ + +#include <sys/cdefs.h> + +#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 + +#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/libc/iconv/citrus_csmapper.c b/lib/libc/iconv/citrus_csmapper.c new file mode 100644 index 0000000..5e0a01a --- /dev/null +++ b/lib/libc/iconv/citrus_csmapper.c @@ -0,0 +1,383 @@ +/* $FreeBSD$ */ +/* $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> +#include <sys/endian.h> +#include <sys/types.h> +#include <sys/queue.h> + +#include <assert.h> +#include <errno.h> +#include <limits.h> +#include <paths.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "citrus_namespace.h" +#include "citrus_types.h" +#include "citrus_bcs.h" +#include "citrus_region.h" +#include "citrus_lock.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" + +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) +{ + struct _region r; + int ret; + + 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) +{ + struct _citrus_db *db1, *db2, *db3; + struct _region fr, r1, r2; + char buf[LINE_MAX]; + uint32_t val32; + unsigned long norm; + int i, num, ret; + + 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) +{ + struct zone z1, z2; + char buf[20]; + 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) +{ + struct _lookup *cl; + struct parse_arg padst; + struct _region data; + int ret; + + 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) +{ + struct _lookup *cl; + struct _region data; + struct parse_arg pa; + char pivot_min[PATH_MAX]; + unsigned long norm_min; + int ret; + + 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; + + WLOCK; + 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: + UNLOCK; + 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) +{ + const char *realsrc, *realdst; + char buf1[PATH_MAX], buf2[PATH_MAX], key[PATH_MAX], pivot[PATH_MAX]; + unsigned long norm; + int ret; + + norm = 0; + + 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/libc/iconv/citrus_csmapper.h b/lib/libc/iconv/citrus_csmapper.h new file mode 100644 index 0000000..dd178da --- /dev/null +++ b/lib/libc/iconv/citrus_csmapper.h @@ -0,0 +1,48 @@ +/* $FreeBSD$ */ +/* $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/libc/iconv/citrus_db.c b/lib/libc/iconv/citrus_db.c new file mode 100644 index 0000000..2de848b --- /dev/null +++ b/lib/libc/iconv/citrus_db.c @@ -0,0 +1,331 @@ +/* $FreeBSD$ */ +/* $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> +#include <sys/endian.h> +#include <sys/types.h> + +#include <assert.h> +#include <errno.h> +#include <limits.h> +#include <stdio.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_mmap.h" +#include "citrus_db.h" +#include "citrus_db_factory.h" +#include "citrus_db_file.h" + +struct _citrus_db { + struct _region db_region; + _citrus_db_hash_func_t db_hashfunc; + void *db_hashfunc_closure; +}; + +int +_citrus_db_open(struct _citrus_db **rdb, struct _region *r, const char *magic, + _citrus_db_hash_func_t hashfunc, void *hashfunc_closure) +{ + struct _citrus_db *db; + struct _citrus_db_header_x *dhx; + struct _memstream ms; + + _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) +{ + struct _citrus_db_entry_x *dex; + struct _citrus_db_header_x *dhx; + struct _citrus_region r; + struct _memstream ms; + uint32_t hashval, num_entries; + size_t offset; + + _memstream_bind(&ms, &db->db_region); + + dhx = _memstream_getregion(&ms, NULL, sizeof(*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(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, __DECONST(void *, 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) +{ + struct _region r; + int ret; + + 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) +{ + struct _region r; + int ret; + 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) +{ + struct _region r; + uint32_t val; + int ret; + + 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) +{ + struct _region r; + int ret; + + 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 _citrus_db_header_x *dhx; + struct _memstream ms; + + _memstream_bind(&ms, &db->db_region); + + dhx = _memstream_getregion(&ms, NULL, sizeof(*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) +{ + struct _citrus_db_entry_x *dex; + struct _citrus_db_header_x *dhx; + struct _memstream ms; + uint32_t num_entries; + size_t offset; + + _memstream_bind(&ms, &db->db_region); + + dhx = _memstream_getregion(&ms, NULL, sizeof(*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/libc/iconv/citrus_db.h b/lib/libc/iconv/citrus_db.h new file mode 100644 index 0000000..27e16f3 --- /dev/null +++ b/lib/libc/iconv/citrus_db.h @@ -0,0 +1,70 @@ +/* $FreeBSD$ */ +/* $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_ + +#include "citrus_db_factory.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 *, _citrus_db_hash_func_t, 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/libc/iconv/citrus_db_factory.c b/lib/libc/iconv/citrus_db_factory.c new file mode 100644 index 0000000..9a3edf2 --- /dev/null +++ b/lib/libc/iconv/citrus_db_factory.c @@ -0,0 +1,348 @@ +/* $FreeBSD$ */ +/* $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. + */ + +#include <sys/cdefs.h> +#include <sys/types.h> +#include <sys/queue.h> + +#include <arpa/inet.h> +#include <assert.h> +#include <errno.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "citrus_namespace.h" +#include "citrus_region.h" +#include "citrus_db_file.h" +#include "citrus_db_factory.h" + +struct _citrus_db_factory_entry { + STAILQ_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; + STAILQ_HEAD(, _citrus_db_factory_entry) df_entries; + size_t df_total_key_size; + size_t df_total_data_size; + uint32_t (*df_hashfunc)(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; + STAILQ_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 = STAILQ_FIRST(&df->df_entries)) != NULL) { + STAILQ_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(key); + de->de_key = *key; + de->de_key_free = keyfree; + de->de_data = *data; + de->de_data_free = datafree; + de->de_idx = -1; + + STAILQ_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) +{ + struct _citrus_db_factory_entry *de, **depp, *det; + size_t dataofs, i, keyofs, nextofs, ofs; + + 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 */ + STAILQ_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; + STAILQ_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/libc/iconv/citrus_db_factory.h b/lib/libc/iconv/citrus_db_factory.h new file mode 100644 index 0000000..b98b19c --- /dev/null +++ b/lib/libc/iconv/citrus_db_factory.h @@ -0,0 +1,57 @@ +/* $FreeBSD$ */ +/* $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)(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/libc/iconv/citrus_db_file.h b/lib/libc/iconv/citrus_db_file.h new file mode 100644 index 0000000..aed07e8 --- /dev/null +++ b/lib/libc/iconv/citrus_db_file.h @@ -0,0 +1,85 @@ +/* $FreeBSD$ */ +/* $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/libc/iconv/citrus_db_hash.c b/lib/libc/iconv/citrus_db_hash.c new file mode 100644 index 0000000..2c599ff --- /dev/null +++ b/lib/libc/iconv/citrus_db_hash.c @@ -0,0 +1,64 @@ +/* $FreeBSD$ */ +/* $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. + */ + +#include <sys/cdefs.h> +#include <sys/types.h> + +#include <assert.h> +#include <stdio.h> +#include <string.h> + +#include "citrus_namespace.h" +#include "citrus_types.h" +#include "citrus_bcs.h" +#include "citrus_region.h" +#include "citrus_db_hash.h" + +uint32_t +_citrus_db_hash_std(struct _region *r) +{ + const uint8_t *p; + uint32_t hash, tmp; + size_t i; + + hash = 0; + p = _region_head(r); + + 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/libc/iconv/citrus_db_hash.h b/lib/libc/iconv/citrus_db_hash.h new file mode 100644 index 0000000..549af26 --- /dev/null +++ b/lib/libc/iconv/citrus_db_hash.h @@ -0,0 +1,37 @@ +/* $FreeBSD$ */ +/* $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(struct _citrus_region *); +__END_DECLS + +#endif diff --git a/lib/libc/iconv/citrus_esdb.c b/lib/libc/iconv/citrus_esdb.c new file mode 100644 index 0000000..578cbc1 --- /dev/null +++ b/lib/libc/iconv/citrus_esdb.c @@ -0,0 +1,374 @@ +/* $FreeBSD$ */ +/* $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> +#include <sys/types.h> + +#include <assert.h> +#include <errno.h> +#include <limits.h> +#include <paths.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.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) +{ + struct _citrus_db *db; + const char *str; + char buf[100]; + uint32_t csid, i, num_charsets, tmp, version; + int ret; + + /* 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) +{ + struct _region fr; + const char *realname, *encfile; + char buf1[PATH_MAX], buf2[PATH_MAX], path[PATH_MAX]; + int ret; + + 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) +{ + + for (int 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) +{ + + for (size_t 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, bool sorted) +{ + struct _citrus_lookup *cla, *cld; + struct _region key, data; + char **list, **q; + char buf[PATH_MAX]; + size_t num; + int ret; + + 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, &data)) == 0) { + if (sorted) + snprintf(buf, sizeof(buf), "%.*s/%.*s", + (int)_region_size(&data), + (const char *)_region_head(&data), + (int)_region_size(&key), + (const char *)_region_head(&key)); + else + snprintf(buf, sizeof(buf), "%.*s/%.*s", + (int)_region_size(&data), + (const char *)_region_head(&data), + (int)_region_size(&key), + (const char *)_region_head(&key)); + _bcs_convert_to_upper(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, &data)) == 0) { + if (!sorted) + snprintf(buf, sizeof(buf), "%.*s", + (int)_region_size(&key), + (const char *)_region_head(&key)); + else { + /* check duplicated entry */ + char *p; + char buf1[PATH_MAX]; + + snprintf(buf1, sizeof(buf1), "%.*s", + (int)_region_size(&data), + (const char *)_region_head(&data)); + if ((p = strchr(buf1, '/')) != NULL) + memcpy(buf1, p + 1, strlen(p) - 1); + if ((p = strstr(buf1, ".esdb")) != NULL) + *p = '\0'; + snprintf(buf, sizeof(buf), "%s/%.*s", buf1, + (int)_region_size(&key), + (const char *)_region_head(&key)); + } + _bcs_convert_to_upper(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; + /* XXX: why reallocing the list space posteriorly? + shouldn't be done earlier? */ + 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/libc/iconv/citrus_esdb.h b/lib/libc/iconv/citrus_esdb.h new file mode 100644 index 0000000..f82a398 --- /dev/null +++ b/lib/libc/iconv/citrus_esdb.h @@ -0,0 +1,58 @@ +/* $FreeBSD$ */ +/* $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_ + +#include "citrus_types.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 *, bool); +__END_DECLS + +#endif diff --git a/lib/libc/iconv/citrus_esdb_file.h b/lib/libc/iconv/citrus_esdb_file.h new file mode 100644 index 0000000..98609d1 --- /dev/null +++ b/lib/libc/iconv/citrus_esdb_file.h @@ -0,0 +1,45 @@ +/* $FreeBSD$ */ +/* $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/libc/iconv/citrus_fix_grouping.h b/lib/libc/iconv/citrus_fix_grouping.h new file mode 100644 index 0000000..fbb1788 --- /dev/null +++ b/lib/libc/iconv/citrus_fix_grouping.h @@ -0,0 +1,53 @@ +/* $FreeBSD$ */ +/* $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; + + 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(__DECONST(void *, grouping)) +#else +#define _CITRUS_FIXUP_CHAR_MAX_MD(grouping) /* nothing to do */ +#endif + +#endif /*_CITRUS_FIX_GROUPING_H_*/ diff --git a/lib/libc/iconv/citrus_hash.c b/lib/libc/iconv/citrus_hash.c new file mode 100644 index 0000000..4db1bda --- /dev/null +++ b/lib/libc/iconv/citrus_hash.c @@ -0,0 +1,51 @@ +/* $FreeBSD$ */ +/* $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> +#include <sys/types.h> + +#include <assert.h> +#include <stdio.h> +#include <string.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, __DECONST(void *, key), strlen(key)); + + return ((int)(_db_hash_std(&r) % (uint32_t)hashsize)); +} diff --git a/lib/libc/iconv/citrus_hash.h b/lib/libc/iconv/citrus_hash.h new file mode 100644 index 0000000..c3e7311 --- /dev/null +++ b/lib/libc/iconv/citrus_hash.h @@ -0,0 +1,59 @@ +/* $FreeBSD$ */ +/* $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 (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 (0) + +__BEGIN_DECLS +int _citrus_string_hash_func(const char *, int); +__END_DECLS + +#endif diff --git a/lib/libc/iconv/citrus_iconv.c b/lib/libc/iconv/citrus_iconv.c new file mode 100644 index 0000000..941ee02 --- /dev/null +++ b/lib/libc/iconv/citrus_iconv.c @@ -0,0 +1,335 @@ +/* $FreeBSD$ */ +/* $NetBSD: citrus_iconv.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> +#include <sys/types.h> +#include <sys/queue.h> + +#include <assert.h> +#include <dirent.h> +#include <errno.h> +#include <iconv.h> +#include <langinfo.h> +#include <limits.h> +#include <paths.h> +#include <stdbool.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#include "citrus_namespace.h" +#include "citrus_bcs.h" +#include "citrus_esdb.h" +#include "citrus_region.h" +#include "citrus_memstream.h" +#include "citrus_mmap.h" +#include "citrus_module.h" +#include "citrus_lock.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" + +static bool isinit = false; +static int shared_max_reuse, shared_num_unused; +static _CITRUS_HASH_HEAD(, _citrus_iconv_shared, CI_HASH_SIZE) shared_pool; +static TAILQ_HEAD(, _citrus_iconv_shared) shared_unused; + +static __inline void +init_cache(void) +{ + + WLOCK; + 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 = true; + } + UNLOCK; +} + +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 convname, const char * __restrict src, + const char * __restrict dst) +{ + struct _citrus_iconv_shared *ci; + _citrus_iconv_getops_t getops; + const char *module; + size_t len_convname; + int ret; + + module = (strcmp(src, dst) != 0) ? "iconv_std" : "iconv_none"; + + /* 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); + if (ret) + 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, src, dst); + 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 *src, const char *dst) +{ + struct _citrus_iconv_shared * ci; + char convname[PATH_MAX]; + int hashval, ret = 0; + + snprintf(convname, sizeof(convname), "%s/%s", src, dst); + + WLOCK; + + /* 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, 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: + UNLOCK; + + return (ret); +} + +static void +release_shared(struct _citrus_iconv_shared * __restrict ci) +{ + + WLOCK; + 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); + TAILQ_REMOVE(&shared_unused, ci, ci_tailq_entry); + _CITRUS_HASH_REMOVE(ci, ci_hash_entry); + shared_num_unused--; + close_shared(ci); + } + } + + UNLOCK; +} + +/* + * _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 src, const char * __restrict dst) +{ + struct _citrus_iconv *cv; + struct _citrus_iconv_shared *ci = NULL; + char realdst[PATH_MAX], realsrc[PATH_MAX]; + char buf[PATH_MAX], path[PATH_MAX]; + int ret; + + init_cache(); + + /* GNU behaviour, using locale encoding if "" or "char" is specified */ + if ((strcmp(src, "") == 0) || (strcmp(src, "char") == 0)) + src = nl_langinfo(CODESET); + if ((strcmp(dst, "") == 0) || (strcmp(dst, "char") == 0)) + dst = nl_langinfo(CODESET); + + /* resolve codeset name aliases */ + 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, realsrc, realdst); + if (ret) + return (ret); + + /* create/init context */ + if (*rcv == NULL) { + cv = malloc(sizeof(*cv)); + if (cv == NULL) { + ret = errno; + release_shared(ci); + return (ret); + } + *rcv = cv; + } + (*rcv)->cv_shared = ci; + ret = (*ci->ci_ops->io_init_context)(*rcv); + if (ret) { + release_shared(ci); + free(*rcv); + return (ret); + } + 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); + } +} + +const char +*_citrus_iconv_canonicalize(const char *name) +{ + char *buf; + + if ((buf = malloc((size_t)PATH_MAX)) == NULL) + return (NULL); + memset((void *)buf, 0, (size_t)PATH_MAX); + _citrus_esdb_alias(name, buf, (size_t)PATH_MAX); + return (buf); +} diff --git a/lib/libc/iconv/citrus_iconv.h b/lib/libc/iconv/citrus_iconv.h new file mode 100644 index 0000000..99604e9 --- /dev/null +++ b/lib/libc/iconv/citrus_iconv.h @@ -0,0 +1,64 @@ +/* $FreeBSD$ */ +/* $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); +void _citrus_iconv_close(struct _citrus_iconv *); +const char *_citrus_iconv_canonicalize(const char *); +__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, + char * __restrict * __restrict in, size_t * __restrict inbytes, + char * __restrict * __restrict out, size_t * __restrict outbytes, + uint32_t flags, size_t * __restrict nresults) +{ + + return (*cv->cv_shared->ci_ops->io_convert)(cv, in, inbytes, out, + outbytes, flags, nresults); +} + +#endif diff --git a/lib/libc/iconv/citrus_iconv_local.h b/lib/libc/iconv/citrus_iconv_local.h new file mode 100644 index 0000000..db20363 --- /dev/null +++ b/lib/libc/iconv/citrus_iconv_local.h @@ -0,0 +1,107 @@ +/* $FreeBSD$ */ +/* $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_ + +#include <iconv.h> + +#define _CITRUS_ICONV_GETOPS_FUNC_BASE(_n_) \ + int _n_(struct _citrus_iconv_ops *) +#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); \ +static void _citrus_##_m_##_iconv_uninit_shared \ + (struct _citrus_iconv_shared *); \ +static int _citrus_##_m_##_iconv_convert \ + (struct _citrus_iconv * __restrict, \ + 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_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); +typedef void (*_citrus_iconv_uninit_shared_t) + (struct _citrus_iconv_shared *); +typedef int (*_citrus_iconv_convert_t) + (struct _citrus_iconv * __restrict, + 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 { + _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; +}; + +struct _citrus_iconv_shared { + struct _citrus_iconv_ops *ci_ops; + void *ci_closure; + _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; + bool ci_discard_ilseq; + struct iconv_hooks *ci_hooks; +}; + +struct _citrus_iconv { + struct _citrus_iconv_shared *cv_shared; + void *cv_closure; +}; + +#endif diff --git a/lib/libc/iconv/citrus_lock.h b/lib/libc/iconv/citrus_lock.h new file mode 100644 index 0000000..ad9443a --- /dev/null +++ b/lib/libc/iconv/citrus_lock.h @@ -0,0 +1,35 @@ +/* $FreeBSD$ */ +/*- + * Copyright (C) 2010 Gabor Kovesdan <gabor@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 <pthread.h> + +static pthread_rwlock_t lock; + +#define WLOCK if (__isthreaded) \ + pthread_rwlock_wrlock(&lock); +#define UNLOCK if (__isthreaded) \ + pthread_rwlock_unlock(&lock); diff --git a/lib/libc/iconv/citrus_lookup.c b/lib/libc/iconv/citrus_lookup.c new file mode 100644 index 0000000..09b1298 --- /dev/null +++ b/lib/libc/iconv/citrus_lookup.c @@ -0,0 +1,362 @@ +/* $FreeBSD$ */ +/* $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> +#include <sys/types.h> + +#include <assert.h> +#include <dirent.h> +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <paths.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.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) +{ + struct _region r; + char path[PATH_MAX]; + int ret; + + 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, __DECONST(void *, p), (size_t)(q - p)); + p = _bcs_skip_ws_len(q, &len); + if (data) + _region_init(data, len ? __DECONST(void *, 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, __DECONST(void *, 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) +{ + struct _citrus_lookup *cl; + struct _region data; + int ret; + + 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/libc/iconv/citrus_lookup.h b/lib/libc/iconv/citrus_lookup.h new file mode 100644 index 0000000..e7a7150 --- /dev/null +++ b/lib/libc/iconv/citrus_lookup.h @@ -0,0 +1,64 @@ +/* $FreeBSD$ */ +/* $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/libc/iconv/citrus_lookup_factory.c b/lib/libc/iconv/citrus_lookup_factory.c new file mode 100644 index 0000000..ec5a5d6 --- /dev/null +++ b/lib/libc/iconv/citrus_lookup_factory.c @@ -0,0 +1,121 @@ +/* $FreeBSD$ */ +/* $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. + */ + +#include <sys/cdefs.h> + +#include <assert.h> +#include <ctype.h> +#include <errno.h> +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.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 data[LINE_MAX], key[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) +{ + void *ptr; + size_t size; + + 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/libc/iconv/citrus_lookup_factory.h b/lib/libc/iconv/citrus_lookup_factory.h new file mode 100644 index 0000000..9016de5 --- /dev/null +++ b/lib/libc/iconv/citrus_lookup_factory.h @@ -0,0 +1,37 @@ +/* $FreeBSD$ */ +/* $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/libc/iconv/citrus_lookup_file.h b/lib/libc/iconv/citrus_lookup_file.h new file mode 100644 index 0000000..43944b3 --- /dev/null +++ b/lib/libc/iconv/citrus_lookup_file.h @@ -0,0 +1,35 @@ +/* $FreeBSD$ */ +/* $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/libc/iconv/citrus_mapper.c b/lib/libc/iconv/citrus_mapper.c new file mode 100644 index 0000000..a788a9d9 --- /dev/null +++ b/lib/libc/iconv/citrus_mapper.c @@ -0,0 +1,397 @@ +/* $FreeBSD$ */ +/* $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> +#include <sys/types.h> +#include <sys/stat.h> +#include <sys/queue.h> + +#include <assert.h> +#include <errno.h> +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> + +#include "citrus_namespace.h" +#include "citrus_types.h" +#include "citrus_region.h" +#include "citrus_lock.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 + +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 _citrus_mapper_area *ma; + struct stat st; + char path[PATH_MAX]; + int ret; + + WLOCK; + + 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: + UNLOCK; + + 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; + const char *cp, *cq; + char *p; + char path[PATH_MAX]; + size_t len; + int ret; + + /* 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) +{ + struct _citrus_mapper *cm; + _citrus_mapper_getops_t getops; + int ret; + + /* 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); + 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) +{ + struct _citrus_mapper *cm; + char linebuf[PATH_MAX]; + const char *module, *variable; + int hashval, ret; + + variable = NULL; + + WLOCK; + + /* 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; + _mapper_close(cm); + goto quit; + } + + /* insert to the cache */ + cm->cm_refcount = 1; + _CITRUS_HASH_INSERT(&ma->ma_cache, cm, cm_entry, hashval); + + *rcm = cm; + ret = 0; +quit: + UNLOCK; + + return (ret); +} + +/* + * _citrus_mapper_close: + * close the specified mapper. + */ +void +_citrus_mapper_close(struct _citrus_mapper *cm) +{ + + if (cm) { + WLOCK; + 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); + } + mapper_close(cm); +quit: + UNLOCK; + } +} + +/* + * _citrus_mapper_set_persistent: + * set persistent count. + */ +void +_citrus_mapper_set_persistent(struct _citrus_mapper * __restrict cm) +{ + + WLOCK; + cm->cm_refcount = REFCOUNT_PERSISTENT; + UNLOCK; +} diff --git a/lib/libc/iconv/citrus_mapper.h b/lib/libc/iconv/citrus_mapper.h new file mode 100644 index 0000000..429b2a1 --- /dev/null +++ b/lib/libc/iconv/citrus_mapper.h @@ -0,0 +1,131 @@ +/* $FreeBSD$ */ +/* $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) +{ + + 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) +{ + + (*cm->cm_ops->mo_init_state)(); +} + +/* + * _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) +{ + + 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) +{ + + 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) +{ + + return (cm->cm_traits->mt_dst_max); +} + +#endif diff --git a/lib/libc/iconv/citrus_mapper_local.h b/lib/libc/iconv/citrus_mapper_local.h new file mode 100644 index 0000000..887a35d --- /dev/null +++ b/lib/libc/iconv/citrus_mapper_local.h @@ -0,0 +1,96 @@ +/* $FreeBSD$ */ +/* $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 *) +#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 \ + (void); + +#define _CITRUS_MAPPER_DEF_OPS(_m_) \ +struct _citrus_mapper_ops _citrus_##_m_##_mapper_ops = { \ + /* 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)(void); + +struct _citrus_mapper_ops { + _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/libc/iconv/citrus_memstream.c b/lib/libc/iconv/citrus_memstream.c new file mode 100644 index 0000000..d7ad4fd --- /dev/null +++ b/lib/libc/iconv/citrus_memstream.c @@ -0,0 +1,148 @@ +/* $FreeBSD$ */ +/* $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> + +#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) +{ + const uint8_t *h, *p; + size_t ret; + int i; + + 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 keylen, len; + + keylen = strlen(key); + for(;;) { + 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 *chr, *head; + 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/libc/iconv/citrus_memstream.h b/lib/libc/iconv/citrus_memstream.h new file mode 100644 index 0000000..cd5ef13 --- /dev/null +++ b/lib/libc/iconv/citrus_memstream.h @@ -0,0 +1,226 @@ +/* $FreeBSD$ */ +/* $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; + + 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, __DECONST(void *, ptr), sz); + + return (ptr == NULL); +} + +#endif diff --git a/lib/libc/iconv/citrus_mmap.c b/lib/libc/iconv/citrus_mmap.c new file mode 100644 index 0000000..dd5d059 --- /dev/null +++ b/lib/libc/iconv/citrus_mmap.c @@ -0,0 +1,97 @@ +/* $FreeBSD$ */ +/* $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> +#include <sys/mman.h> +#include <sys/types.h> +#include <sys/stat.h> + +#include <assert.h> +#include <errno.h> +#include <fcntl.h> +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.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) +{ + struct stat st; + void *head; + int fd, ret; + + ret = 0; + + _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) +{ + + if (_region_head(r) != NULL) { + (void)munmap(_region_head(r), _region_size(r)); + _region_init(r, NULL, 0); + } +} diff --git a/lib/libc/iconv/citrus_mmap.h b/lib/libc/iconv/citrus_mmap.h new file mode 100644 index 0000000..590e7fb --- /dev/null +++ b/lib/libc/iconv/citrus_mmap.h @@ -0,0 +1,40 @@ +/* $FreeBSD$ */ +/* $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/libc/iconv/citrus_module.c b/lib/libc/iconv/citrus_module.c new file mode 100644 index 0000000..aa96aba --- /dev/null +++ b/lib/libc/iconv/citrus_module.c @@ -0,0 +1,314 @@ +/* $FreeBSD$ */ +/* $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> +#include <sys/types.h> + +#include <assert.h> +#include <dirent.h> +#include <dlfcn.h> +#include <errno.h> +#include <limits.h> +#include <paths.h> +#include <stdbool.h> +#include <stddef.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <unistd.h> + +#define I18NMODULE_MAJOR 4 + +#include "citrus_namespace.h" +#include "citrus_bcs.h" +#include "citrus_module.h" + +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; + + 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) +{ + int i; + + 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); + + /* cannot happen */ + return (0); +} + +static const char * +_findshlib(char *name, int *majorp, int *minorp) +{ + char *lname; + const char *search_dirs[1]; + static char path[PATH_MAX]; + int dewey[MAXDEWEY], tmp[MAXDEWEY]; + int i, len, major, minor, ndewey, n_search_dirs; + + n_search_dirs = 1; + 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++) { + struct dirent *dp; + DIR *dd = opendir(search_dirs[i]); + int found_dot_a = 0, found_dot_so = 0; + + if (dd == NULL) + break; + + 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; + + snprintf(name, sizeof(name), "_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]; + void *handle; + int maj, min; + + 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) { + printf("%s", dlerror()); + return (EINVAL); + } + + *rhandle = (_citrus_module_t)handle; + + return (0); +} + +void +_citrus_unload_module(_citrus_module_t handle) +{ + + if (handle) + dlclose((void *)handle); +} diff --git a/lib/libc/iconv/citrus_module.h b/lib/libc/iconv/citrus_module.h new file mode 100644 index 0000000..b004b87 --- /dev/null +++ b/lib/libc/iconv/citrus_module.h @@ -0,0 +1,54 @@ +/* $FreeBSD$ */ +/* $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_ + +#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 (0) + +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/libc/iconv/citrus_namespace.h b/lib/libc/iconv/citrus_namespace.h new file mode 100644 index 0000000..6e9ffe0 --- /dev/null +++ b/lib/libc/iconv/citrus_namespace.h @@ -0,0 +1,241 @@ +/* $FreeBSD$ */ +/* $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. + */ + +#include "citrus_bcs.h" + +#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/libc/iconv/citrus_none.c b/lib/libc/iconv/citrus_none.c new file mode 100644 index 0000000..1f77ad0 --- /dev/null +++ b/lib/libc/iconv/citrus_none.c @@ -0,0 +1,238 @@ +/* $FreeBSD$ */ +/* $NetBSD: citrus_none.c,v 1.18 2008/06/14 16:01:07 tnozaki Exp $ */ + +/*- + * Copyright (c) 2002 Citrus Project, + * Copyright (c) 2010 Gabor Kovesdan <gabor@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> +#include <sys/types.h> + +#include <assert.h> +#include <errno.h> +#include <iconv.h> +#include <stddef.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <wchar.h> + +#include "citrus_namespace.h" +#include "citrus_types.h" +#include "citrus_module.h" +#include "citrus_none.h" +#include "citrus_stdenc.h" + +_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 +_citrus_NONE_stdenc_init(struct _citrus_stdenc * __restrict ce, + const void *var __unused, size_t lenvar __unused, + 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 +_citrus_NONE_stdenc_uninit(struct _citrus_stdenc *ce __unused) +{ + +} + +static int +_citrus_NONE_stdenc_init_state(struct _citrus_stdenc * __restrict ce __unused, + void * __restrict ps __unused) +{ + + return (0); +} + +static int +_citrus_NONE_stdenc_mbtocs(struct _citrus_stdenc * __restrict ce __unused, + _csid_t *csid, _index_t *idx, char **s, size_t n, + void *ps __unused, size_t *nresult, struct iconv_hooks *hooks) +{ + + if (n < 1) { + *nresult = (size_t)-2; + return (0); + } + + *csid = 0; + *idx = (_index_t)(unsigned char)*(*s)++; + *nresult = *idx == 0 ? 0 : 1; + + if ((hooks != NULL) && (hooks->uc_hook != NULL)) + hooks->uc_hook((unsigned int)*idx, hooks->data); + + return (0); +} + +static int +_citrus_NONE_stdenc_cstomb(struct _citrus_stdenc * __restrict ce __unused, + char *s, size_t n, _csid_t csid, _index_t idx, void *ps __unused, + size_t *nresult, struct iconv_hooks *hooks __unused) +{ + + if (csid == _CITRUS_CSID_INVALID) { + *nresult = 0; + return (0); + } + if (csid != 0) + return (EILSEQ); + + if ((idx & 0x000000FF) == idx) { + if (n < 1) { + *nresult = (size_t)-1; + return (E2BIG); + } + *s = (char)idx; + *nresult = 1; + } else if ((idx & 0x0000FFFF) == idx) { + if (n < 2) { + *nresult = (size_t)-1; + return (E2BIG); + } + s[0] = (char)idx; + /* XXX: might be endian dependent */ + s[1] = (char)(idx >> 8); + *nresult = 2; + } else if ((idx & 0x00FFFFFF) == idx) { + if (n < 3) { + *nresult = (size_t)-1; + return (E2BIG); + } + s[0] = (char)idx; + /* XXX: might be endian dependent */ + s[1] = (char)(idx >> 8); + s[2] = (char)(idx >> 16); + *nresult = 3; + } else { + if (n < 3) { + *nresult = (size_t)-1; + return (E2BIG); + } + s[0] = (char)idx; + /* XXX: might be endian dependent */ + s[1] = (char)(idx >> 8); + s[2] = (char)(idx >> 16); + s[3] = (char)(idx >> 24); + *nresult = 4; + } + + return (0); +} + +static int +_citrus_NONE_stdenc_mbtowc(struct _citrus_stdenc * __restrict ce __unused, + _wc_t * __restrict pwc, char ** __restrict s, size_t n, + void * __restrict pspriv __unused, size_t * __restrict nresult, + struct iconv_hooks *hooks) +{ + + 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; + + if ((hooks != NULL) && (hooks->wc_hook != NULL)) + hooks->wc_hook(*pwc, hooks->data); + + return (0); +} + +static int +_citrus_NONE_stdenc_wctomb(struct _citrus_stdenc * __restrict ce __unused, + char * __restrict s, size_t n, _wc_t wc, + void * __restrict pspriv __unused, size_t * __restrict nresult, + struct iconv_hooks *hooks __unused) +{ + int ret; + + if ((wc & ~0xFFU) != 0) { + *nresult = (size_t)-1; + return (EILSEQ); + } + if (n == 0) { + *nresult = (size_t)-1; + ret = E2BIG; + } + + *nresult = 1; + if (s != NULL && n > 0) + *s = (char)wc; + + return (0); +} + +static int +_citrus_NONE_stdenc_put_state_reset(struct _citrus_stdenc * __restrict ce __unused, + char * __restrict s __unused, size_t n __unused, + void * __restrict pspriv __unused, size_t * __restrict nresult) +{ + + *nresult = 0; + + return (0); +} + +static int +_citrus_NONE_stdenc_get_state_desc(struct _stdenc * __restrict ce __unused, + void * __restrict ps __unused, 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/libc/iconv/citrus_none.h b/lib/libc/iconv/citrus_none.h new file mode 100644 index 0000000..20d2791 --- /dev/null +++ b/lib/libc/iconv/citrus_none.h @@ -0,0 +1,36 @@ +/* $FreeBSD$ */ +/* $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_stdenc_ops _citrus_NONE_stdenc_ops; +extern struct _citrus_stdenc_traits _citrus_NONE_stdenc_traits; + +#endif diff --git a/lib/libc/iconv/citrus_pivot_factory.c b/lib/libc/iconv/citrus_pivot_factory.c new file mode 100644 index 0000000..0f279b1 --- /dev/null +++ b/lib/libc/iconv/citrus_pivot_factory.c @@ -0,0 +1,225 @@ +/* $FreeBSD$ */ +/* $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. + */ + +#include <sys/cdefs.h> +#include <sys/queue.h> + +#include <assert.h> +#include <ctype.h> +#include <errno.h> +#include <limits.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.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; + STAILQ_ENTRY(src_entry) se_entry; +}; +STAILQ_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; + + STAILQ_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); + } + STAILQ_INSERT_TAIL(sh, se, se_entry); + *rse = se; + + return (0); +} + +static void +free_src(struct src_head *sh) +{ + struct src_entry *se; + + while ((se = STAILQ_FIRST(sh)) != NULL) { + STAILQ_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) +{ + struct src_entry *se; + const char *p; + char key1[LINE_MAX], key2[LINE_MAX], data[LINE_MAX]; + char *ep; + uint32_t val; + int ret; + + se = NULL; + + /* 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) +{ + struct _db_factory *df; + struct src_entry *se; + struct _region subr; + void *ptr; + size_t size; + int ret; + + ret = _db_factory_create(&df, &_db_hash_std, NULL); + if (ret) + return (ret); + + STAILQ_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; + + STAILQ_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/libc/iconv/citrus_pivot_factory.h b/lib/libc/iconv/citrus_pivot_factory.h new file mode 100644 index 0000000..76f0f70 --- /dev/null +++ b/lib/libc/iconv/citrus_pivot_factory.h @@ -0,0 +1,37 @@ +/* $FreeBSD$ */ +/* $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/libc/iconv/citrus_pivot_file.h b/lib/libc/iconv/citrus_pivot_file.h new file mode 100644 index 0000000..454e93a --- /dev/null +++ b/lib/libc/iconv/citrus_pivot_file.h @@ -0,0 +1,36 @@ +/* $FreeBSD$ */ +/* $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/libc/iconv/citrus_prop.c b/lib/libc/iconv/citrus_prop.c new file mode 100644 index 0000000..c2d4829 --- /dev/null +++ b/lib/libc/iconv/citrus_prop.c @@ -0,0 +1,444 @@ +/* $FreeBSD$ */ +/* $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> + +#include <assert.h> +#include <errno.h> +#include <limits.h> +#include <stdbool.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 chr; + bool boolean; + 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) +{ + + obj->type = type; + memset(&obj->u, 0, sizeof(obj->u)); +} + +static __inline void +_citrus_prop_object_uninit(_citrus_prop_object_t *obj) +{ + + if (obj->type == _CITRUS_PROP_STR) + free(__DECONST(void *, 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 ch, cutlim, n; \ + char *p; \ + \ + 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 base, ch, neg; \ + \ + _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 base, ch; + + 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; + case '0': case '1': case '2': case '3': + case '4': case '5': case '6': case '7': + _memstream_ungetc(ms, ch); + base -= 8; + /*FALLTHROUGH*/ + case 'x': + return (_citrus_prop_read_chr_common(ms, result, base)); + /*NOTREACHED*/ + 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; + + _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) +{ + + _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.boolean = true; + 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.boolean = false; + return (0); + } + } + return (EINVAL); +} + +static int +_citrus_prop_read_str(struct _memstream * __restrict ms, + _citrus_prop_object_t * __restrict obj) +{ + int ch, errnum, quot; + char *s, *t; +#define _CITRUS_PROP_STR_BUFSIZ 512 + size_t m, n; + + 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; + /*NOTREACHED*/ + 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; + + 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; + + 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: + /*FALLTHROUGH*/ + 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 { \ + errnum = (*hint->cb._func_.func)(context, \ + hint->name, ostart.u._func_); \ +} while (0) +#define CALL1(_func_) \ +do { \ + errnum = (*hint->cb._func_.func)(context, \ + hint->name, ostart.u._func_, oend.u._func_);\ +} while (0) + switch (hint->type) { + case _CITRUS_PROP_BOOL: + CALL0(boolean); + 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 ch, errnum; + + _memstream_bind_ptr(&ms, __DECONST(void *, 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 ** __restrict)context); + if (errnum != 0) + return (errnum); + } + return (0); +} diff --git a/lib/libc/iconv/citrus_prop.h b/lib/libc/iconv/citrus_prop.h new file mode 100644 index 0000000..db087a4 --- /dev/null +++ b/lib/libc/iconv/citrus_prop.h @@ -0,0 +1,92 @@ +/* $FreeBSD$ */ +/* $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(boolean, 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(boolean); + _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, { .boolean = { 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, _CITRUS_PROP_NUM, { .num = { 0 } } } + +__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/libc/iconv/citrus_region.h b/lib/libc/iconv/citrus_region.h new file mode 100644 index 0000000..8cecb40 --- /dev/null +++ b/lib/libc/iconv/citrus_region.h @@ -0,0 +1,113 @@ +/* $FreeBSD$ */ +/* $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_ + +#include <sys/types.h> + +struct _citrus_region { + void *r_head; + size_t r_size; +}; + +static __inline void +_citrus_region_init(struct _citrus_region *r, void *h, size_t sz) +{ + + 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/libc/iconv/citrus_stdenc.c b/lib/libc/iconv/citrus_stdenc.c new file mode 100644 index 0000000..b6562f8 --- /dev/null +++ b/lib/libc/iconv/citrus_stdenc.c @@ -0,0 +1,145 @@ +/* $FreeBSD$ */ +/* $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> + +#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_none.h" +#include "citrus_stdenc.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 */ +}; + +int +_citrus_stdenc_open(struct _citrus_stdenc * __restrict * __restrict rce, + char const * __restrict encname, const void * __restrict variable, + size_t lenvar) +{ + struct _citrus_stdenc *ce; + _citrus_module_t handle; + _citrus_stdenc_getops_t getops; + int ret; + + 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)); + if (ret) + goto bad; + + /* 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) +{ + + 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); +} diff --git a/lib/libc/iconv/citrus_stdenc.h b/lib/libc/iconv/citrus_stdenc.h new file mode 100644 index 0000000..50f4dff --- /dev/null +++ b/lib/libc/iconv/citrus_stdenc.h @@ -0,0 +1,124 @@ +/* $FreeBSD$ */ +/* $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) +{ + + 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, + char ** __restrict s, size_t n, void * __restrict ps, + size_t * __restrict nresult, struct iconv_hooks *hooks) +{ + + return ((*ce->ce_ops->eo_mbtocs)(ce, csid, idx, s, n, ps, nresult, + hooks)); +} + +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, + struct iconv_hooks *hooks) +{ + + return ((*ce->ce_ops->eo_cstomb)(ce, s, n, csid, idx, ps, nresult, + hooks)); +} + +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, struct iconv_hooks *hooks) +{ + + return ((*ce->ce_ops->eo_wctomb)(ce, s, n, wc, ps, nresult, hooks)); +} + +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) +{ + + 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) +{ + + return (ce->ce_traits->et_state_size); +} + +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) +{ + + return ((*ce->ce_ops->eo_get_state_desc)(ce, ps, id, d)); +} +#endif diff --git a/lib/libc/iconv/citrus_stdenc_local.h b/lib/libc/iconv/citrus_stdenc_local.h new file mode 100644 index 0000000..c55387a --- /dev/null +++ b/lib/libc/iconv/citrus_stdenc_local.h @@ -0,0 +1,161 @@ +/* $FreeBSD$ */ +/* $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_ + +#include <iconv.h> + +#include "citrus_module.h" + +#define _CITRUS_STDENC_GETOPS_FUNC_BASE(n) \ + int n(struct _citrus_stdenc_ops *, size_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, \ + char ** __restrict, size_t, \ + void * __restrict, size_t * __restrict, \ + struct iconv_hooks *); \ +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, struct iconv_hooks *); \ +static int _citrus_##_e_##_stdenc_mbtowc \ + (struct _citrus_stdenc * __restrict, \ + _citrus_wc_t * __restrict, \ + char ** __restrict, size_t, \ + void * __restrict, size_t * __restrict, \ + struct iconv_hooks *); \ +static int _citrus_##_e_##_stdenc_wctomb \ + (struct _citrus_stdenc * __restrict, \ + char * __restrict, size_t, _citrus_wc_t, \ + void * __restrict, size_t * __restrict, \ + struct iconv_hooks *); \ +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_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, + char ** __restrict, size_t, + void * __restrict, size_t * __restrict, + struct iconv_hooks *); +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, struct iconv_hooks *); +typedef int (*_citrus_stdenc_mbtowc_t) + (struct _citrus_stdenc * __restrict, + _citrus_wc_t * __restrict, + char ** __restrict, size_t, + void * __restrict, size_t * __restrict, + struct iconv_hooks *); +typedef int (*_citrus_stdenc_wctomb_t) + (struct _citrus_stdenc *__restrict, char * __restrict, size_t, + _citrus_wc_t, void * __restrict, size_t * __restrict, + struct iconv_hooks *); +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); + +struct _citrus_stdenc_ops { + _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 { + /* version 0x00000001 */ + struct _citrus_stdenc_ops *ce_ops; + void *ce_closure; + _citrus_module_t ce_module; + struct _citrus_stdenc_traits *ce_traits; +}; + +#define _CITRUS_DEFAULT_STDENC_NAME "NONE" + +#endif diff --git a/lib/libc/iconv/citrus_stdenc_template.h b/lib/libc/iconv/citrus_stdenc_template.h new file mode 100644 index 0000000..9a05fa7 --- /dev/null +++ b/lib/libc/iconv/citrus_stdenc_template.h @@ -0,0 +1,211 @@ +/* $FreeBSD$ */ +/* $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. + */ + +#include <iconv.h> + +/* + * 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 __unused) +{ + + 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) +{ + _ENCODING_INFO *ei; + int ret; + + 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, + char ** __restrict s, size_t n, void * __restrict ps, + size_t * __restrict nresult, struct iconv_hooks *hooks) +{ + wchar_t wc; + int ret; + + ret = _FUNCNAME(mbrtowc_priv)(_CE_TO_EI(ce), &wc, s, n, + _TO_STATE(ps), nresult); + + if ((ret == 0) && *nresult != (size_t)-2) + ret = _FUNCNAME(stdenc_wctocs)(_CE_TO_EI(ce), csid, idx, wc); + + if ((ret == 0) && (hooks != NULL) && (hooks->uc_hook != NULL)) + hooks->uc_hook((unsigned int)*idx, hooks->data); + 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, + struct iconv_hooks *hooks __unused) +{ + wchar_t wc; + int ret; + + wc = ret = 0; + + if (csid != _CITRUS_CSID_INVALID) + ret = _FUNCNAME(stdenc_cstowc)(_CE_TO_EI(ce), &wc, csid, idx); + + if (ret == 0) + ret = _FUNCNAME(wcrtomb_priv)(_CE_TO_EI(ce), s, n, wc, + _TO_STATE(ps), nresult); + return (ret); +} + +static int +_FUNCNAME(stdenc_mbtowc)(struct _citrus_stdenc * __restrict ce, + _citrus_wc_t * __restrict wc, char ** __restrict s, size_t n, + void * __restrict ps, size_t * __restrict nresult, + struct iconv_hooks *hooks) +{ + int ret; + + ret = _FUNCNAME(mbrtowc_priv)(_CE_TO_EI(ce), wc, s, n, + _TO_STATE(ps), nresult); + if ((ret == 0) && (hooks != NULL) && (hooks->wc_hook != NULL)) + hooks->wc_hook(*wc, hooks->data); + return (ret); +} + +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, struct iconv_hooks *hooks __unused) +{ + int ret; + + ret = _FUNCNAME(wcrtomb_priv)(_CE_TO_EI(ce), s, n, wc, _TO_STATE(ps), + nresult); + return (ret); +} + +static int +_FUNCNAME(stdenc_put_state_reset)(struct _citrus_stdenc * __restrict ce __unused, + char * __restrict s __unused, size_t n __unused, + void * __restrict ps __unused, 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/libc/iconv/citrus_types.h b/lib/libc/iconv/citrus_types.h new file mode 100644 index 0000000..5f9c4e3 --- /dev/null +++ b/lib/libc/iconv/citrus_types.h @@ -0,0 +1,40 @@ +/* $FreeBSD$ */ +/* $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. + */ + +#include <sys/types.h> + +#ifndef _CITRUS_TYPES_H_ +#define _CITRUS_TYPES_H_ + +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/libc/iconv/iconv.3 b/lib/libc/iconv/iconv.3 new file mode 100644 index 0000000..9b658e9 --- /dev/null +++ b/lib/libc/iconv/iconv.3 @@ -0,0 +1,305 @@ +.\" $FreeBSD$ +.\" $NetBSD: iconv.3,v 1.12 2004/08/02 13:38:21 tshiozak Exp $ +.\" +.\" Copyright (c) 2003 Citrus Project, +.\" Copyright (c) 2009, 2010 Gabor Kovesdan <gabor@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. +.\" +.Dd Juny 16, 2010 +.Dt ICONV 3 +.Os +.Sh NAME +.Nm iconv_open , +.Nm iconv_open_into , +.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_open_into "const char *dstname" "const char *srcname" "iconv_allocation_t *ptr" +.Ft int +.Fn iconv_close "iconv_t cd" +.Ft size_t +.Fn iconv "iconv_t cd" "char ** restrict src" "size_t * restrict srcleft" "char ** restrict dst" "size_t * restrict dstleft" +.Ft size_t +.Fn __iconv "iconv_t cd" "const char ** restrict src" "size_t * restrict srcleft" "char ** restrict dst" "size_t * restrict dstleft" "uint32_t flags" "size_t invalids" +.Sh DESCRIPTION +The +.Fn iconv_open +function opens a converter from the codeset +.Fa srcname +to the codeset +.Fa dstname +and returns its descriptor. +The arguments +.Fa srcname +and +.Fa dstname +accept "" and "char", which refer to the current locale encoding. +.Pp +The +.Fn iconv_open_into +creates a conversion descriptor on a preallocated space. +The +.Ft iconv_allocation_t +is used as a spaceholder type when allocating such space. +The +.Fa dstname +and +.Fa srcname +arguments are the same as in the case of +.Fn iconv_open . +The +.Fa ptr +argument is a pointer of +.Ft iconv_allocation_t +to the preallocated space. +.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 +.It *src +Pointer to the byte just after the last character fetched. +.It *srcleft +Number of remaining bytes in the source buffer. +.It *dst +Pointer to the byte just after the last character stored. +.It *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 +There are two special cases of +.Fn iconv : +.Bl -tag -width 0123 +.It "src == NULL || *src == NULL" +If the source and/or destination codesets are stateful, +.Fn iconv +places these into their initial state. +.Pp +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. +.Pp +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. +.Pp +.El +The +.Fn __iconv +function works just like +.Fn iconv +but if +.Fn iconv +fails, the invalid character count is lost there. +This is a not bug rather a limitation of +.St -p1003.1-2008 , +so +.Fn __iconv +is provided as an alternative but non-standard interface. +It also has a flags argument, where currently the following +flags can be passed: +.Bl -tag -width 0123 +.It __ICONV_F_HIDE_INVALID +Skip invalid characters, instead of returning with an error. +.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 errno to indicate the error. +.Pp +Upon successful completion of +.Fn iconv_open_into , +it returns 0. +Otherwise, +.Fn iconv_open_into +returns \-1, and sets 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 ENOMEM +Memory is exhausted. +.It Bq Er EINVAL +There is no converter specified by +.Fa srcname +and +.Fa dstname . +.El +The +.Fn iconv_open_into +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 . +.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 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 E2BIG +The output buffer pointed to by +.Fa *dst +is too small to store the result string. +.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 , +.Xr mkcsmapper 1 , +.Xr mkesdb 1 +.Sh STANDARDS +The +.Fn iconv_open , +.Fn iconv_close , +and +.Fn iconv +functions conform to +.St -p1003.1-2008 . +.Pp +The +.Fn iconv_open_into +function is a GNU-specific extension and it is not part of any standard, +thus its use may break portability. +The +.Fn __iconv +function is an own extension and it is not part of any standard, +thus its use may break portability. diff --git a/lib/libc/iconv/iconv.c b/lib/libc/iconv/iconv.c new file mode 100644 index 0000000..2cd38df --- /dev/null +++ b/lib/libc/iconv/iconv.c @@ -0,0 +1,332 @@ +/* $FreeBSD$ */ +/* $NetBSD: iconv.c,v 1.11 2009/03/03 16:22:33 explorer Exp $ */ + +/*- + * Copyright (c) 2003 Citrus Project, + * Copyright (c) 2009, 2010 Gabor Kovesdan <gabor@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> +#include <sys/queue.h> +#include <sys/types.h> + +#include <assert.h> +#include <errno.h> +#include <iconv.h> +#include <limits.h> +#include <paths.h> +#include <stdbool.h> +#include <stdlib.h> +#include <string.h> + +#include "citrus_types.h" +#include "citrus_module.h" +#include "citrus_esdb.h" +#include "citrus_hash.h" +#include "citrus_iconv.h" + +#ifdef __weak_alias +__weak_alias(libiconv, _iconv) +__weak_alias(libiconv_open, _iconv_open) +__weak_alias(libiconv_open_into, _iconv_open_into) +__weak_alias(libiconv_close, _iconv_close) +__weak_alias(libiconvlist, _iconvlist) +__weak_alias(libiconvctl, _iconvctl) +__weak_alias(libiconv_set_relocation_prefix, _iconv_set_relocation_prefix) +__weak_alias(iconv_canonicalize, _iconv_canonicalize) +#endif + +#define ISBADF(_h_) (!(_h_) || (_h_) == (iconv_t)-1) + +int _libiconv_version = _LIBICONV_VERSION; + +iconv_t _iconv_open(const char *out, const char *in, + struct _citrus_iconv *prealloc); + +iconv_t +_iconv_open(const char *out, const char *in, struct _citrus_iconv *prealloc) +{ + struct _citrus_iconv *handle; + char *out_truncated, *p; + int ret; + + handle = prealloc; + + /* + * Remove anything following a //, as these are options (like + * //ignore, //translate, etc) and we just don't handle them. + * This is for compatibilty with software that uses thees + * blindly. + */ + out_truncated = strdup(out); + if (out_truncated == NULL) { + errno = ENOMEM; + return ((iconv_t)-1); + } + + p = out_truncated; + while (*p != 0) { + if (p[0] == '/' && p[1] == '/') { + *p = '\0'; + break; + } + p++; + } + + ret = _citrus_iconv_open(&handle, in, out_truncated); + free(out_truncated); + if (ret) { + errno = ret == ENOENT ? EINVAL : ret; + return ((iconv_t)-1); + } + + handle->cv_shared->ci_discard_ilseq = strcasestr(out, "//IGNORE"); + handle->cv_shared->ci_hooks = NULL; + + return ((iconv_t)(void *)handle); +} + +iconv_t +libiconv_open(const char *out, const char *in) +{ + + return (_iconv_open(out, in, NULL)); +} + +int +libiconv_open_into(const char *out, const char *in, iconv_allocation_t *ptr) +{ + struct _citrus_iconv *handle; + + handle = (struct _citrus_iconv *)ptr; + return ((_iconv_open(out, in, handle) == (iconv_t)-1) ? -1 : 0); +} + +int +libiconv_close(iconv_t handle) +{ + + if (ISBADF(handle)) { + errno = EBADF; + return (-1); + } + + _citrus_iconv_close((struct _citrus_iconv *)(void *)handle); + + return (0); +} + +size_t +libiconv(iconv_t handle, char **in, size_t *szin, char **out, size_t *szout) +{ + size_t ret; + int err; + + 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, char **in, size_t *szin, char **out, + size_t *szout, uint32_t flags, size_t *invalids) +{ + size_t ret; + int err; + + 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, bool sorted) +{ + int ret; + + ret = _citrus_esdb_get_list(rlist, rsz, sorted); + if (ret) { + errno = ret; + return (-1); + } + + return (0); +} + +void +__iconv_free_list(char **list, size_t sz) +{ + + _citrus_esdb_free_list(list, sz); +} + +/* + * GNU-compatibile non-standard interfaces. + */ +static int +qsort_helper(const void *first, const void *second) +{ + const char * const *s1; + const char * const *s2; + + s1 = first; + s2 = second; + return (strcmp(*s1, *s2)); +} + +void +libiconvlist(int (*do_one) (unsigned int, const char * const *, + void *), void *data) +{ + char **list, **names; + const char * const *np; + char *curitem, *curkey, *slashpos; + size_t sz; + unsigned int i, j; + + i = 0; + + if (__iconv_get_list(&list, &sz, true)) + list = NULL; + qsort((void *)list, sz, sizeof(char *), qsort_helper); + while (i < sz) { + j = 0; + slashpos = strchr(list[i], '/'); + curkey = (char *)malloc(slashpos - list[i] + 2); + names = (char **)malloc(sz * sizeof(char *)); + if ((curkey == NULL) || (names == NULL)) { + __iconv_free_list(list, sz); + return; + } + strlcpy(curkey, list[i], slashpos - list[i] + 1); + names[j++] = strdup(curkey); + for (; (i < sz) && (memcmp(curkey, list[i], strlen(curkey)) == 0); i++) { + slashpos = strchr(list[i], '/'); + curitem = (char *)malloc(strlen(slashpos) + 1); + if (curitem == NULL) { + __iconv_free_list(list, sz); + return; + } + strlcpy(curitem, &slashpos[1], strlen(slashpos) + 1); + if (strcmp(curkey, curitem) == 0) { + continue; + } + names[j++] = strdup(curitem); + } + np = (const char * const *)names; + do_one(j, np, data); + free(names); + } + + __iconv_free_list(list, sz); +} + +__inline const char +*iconv_canonicalize(const char *name) +{ + + return (_citrus_iconv_canonicalize(name)); +} + +int +libiconvctl(iconv_t cd, int request, void *argument) +{ + struct _citrus_iconv *cv; + struct iconv_hooks *hooks; + const char *convname; + char src[PATH_MAX], *dst; + int *i; + + cv = (struct _citrus_iconv *)(void *)cd; + hooks = (struct iconv_hooks *)argument; + i = (int *)argument; + + if (ISBADF(cd)) { + errno = EBADF; + return (-1); + } + + switch (request) { + case ICONV_TRIVIALP: + convname = cv->cv_shared->ci_convname; + dst = strchr(convname, '/'); + + strlcpy(src, convname, dst - convname + 1); + dst++; + if ((convname == NULL) || (src == NULL) || (dst == NULL)) + return (-1); + *i = strcmp(src, dst) == 0 ? 1 : 0; + return (0); + case ICONV_GET_TRANSLITERATE: + *i = 1; + return (0); + case ICONV_SET_TRANSLITERATE: + return ((*i == 1) ? 0 : -1); + case ICONV_GET_DISCARD_ILSEQ: + *i = cv->cv_shared->ci_discard_ilseq ? 1 : 0; + return (0); + case ICONV_SET_DISCARD_ILSEQ: + cv->cv_shared->ci_discard_ilseq = *i; + return (0); + case ICONV_SET_HOOKS: + cv->cv_shared->ci_hooks = hooks; + return (0); + case ICONV_SET_FALLBACKS: + errno = EOPNOTSUPP; + return (-1); + default: + errno = EINVAL; + return (-1); + } +} + +void +libiconv_set_relocation_prefix(const char *orig_prefix __unused, + const char *curr_prefix __unused) +{ + +} diff --git a/lib/libc/iconv/iconv_canonicalize.3 b/lib/libc/iconv/iconv_canonicalize.3 new file mode 100644 index 0000000..3c52ae2 --- /dev/null +++ b/lib/libc/iconv/iconv_canonicalize.3 @@ -0,0 +1,74 @@ +.\" Copyright (c) 2009 Gabor Kovesdan <gabor@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. +.\" +.\" Portions of this text are reprinted and reproduced in electronic form +.\" from IEEE Std 1003.1, 2004 Edition, Standard for Information Technology -- +.\" Portable Operating System Interface (POSIX), The Open Group Base +.\" Specifications Issue 6, Copyright (C) 2001-2004 by the Institute of +.\" Electrical and Electronics Engineers, Inc and The Open Group. In the +.\" event of any discrepancy between this version and the original IEEE and +.\" The Open Group Standard, the original IEEE and The Open Group Standard is +.\" the referee document. The original Standard can be obtained online at +.\" http://www.opengroup.org/unix/online.html. +.\" +.\" $FreeBSD$ +.\" +.Dd October 20, 2009 +.Dt ICONV_CANONICALIZE 3 +.Os +.Sh NAME +.Nm iconv_canonicalize +.Nd resolving character encoding names to canonical form +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In iconv.h +.Ft const char * +.Fn iconv_canonicalize "const char *name" +.Sh DESCRIPTION +The +.Fn iconv_canonicalize +function resolves the character encoding name specified by the +.Fa name +argument to its canonical form. +.Sh RETURN VALUES +Upon successful completion +.Fn iconv_canonicalize , +returns the canonical name of the given encoding. +If the specified name is already a canonical name, the same +value is returned. +If the specified name is not an existing character encoding +name, NULL is returned. +.Sh SEE ALSO +.Xr iconv 3 +.Sh STANDARDS +The +.Nm +function is a non-standard extension, which appeared in +the GNU implementation and was adopted in +.Fx 9 +for compatibility's sake. +.Sh AUTHORS +This manual page was written by +.An Gabor Kovesdan Aq gabor@FreeBSD.org . diff --git a/lib/libc/iconv/iconvctl.3 b/lib/libc/iconv/iconvctl.3 new file mode 100644 index 0000000..29007c1 --- /dev/null +++ b/lib/libc/iconv/iconvctl.3 @@ -0,0 +1,162 @@ +.\" Copyright (c) 2009 Gabor Kovesdan <gabor@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. +.\" +.\" Portions of this text are reprinted and reproduced in electronic form +.\" from IEEE Std 1003.1, 2004 Edition, Standard for Information Technology -- +.\" Portable Operating System Interface (POSIX), The Open Group Base +.\" Specifications Issue 6, Copyright (C) 2001-2004 by the Institute of +.\" Electrical and Electronics Engineers, Inc and The Open Group. In the +.\" event of any discrepancy between this version and the original IEEE and +.\" The Open Group Standard, the original IEEE and The Open Group Standard is +.\" the referee document. The original Standard can be obtained online at +.\" http://www.opengroup.org/unix/online.html. +.\" +.\" $FreeBSD$ +.\" +.Dd November 7, 2009 +.Dt ICONVCTL 3 +.Os +.Sh NAME +.Nm iconvctl +.Nd controlling and diagnostical facility for +.Xr iconv 3 +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In iconv.h +.Ft int +.Fn iconvctl "iconv_t cd" "int request" "void *argument" +.Sh DESCRIPTION +The +.Fn iconvctl +function can retrieve or set specific conversion +setting from the +.Fa cd +conversion descriptor. +The +.Fa request +parameter specifies the operation to accomplish and +.Fa argument +is an operation-specific argument. +.Pp +The possible operations are the following: +.Bl -tag -width -indent +.It ICONV_TRIVIALP +In this case +.Fa argument +is an +.Ft int * +variable, which is set to 1 if the encoding is trivial one, i.e. +the input and output encodings are the same. +Otherwise, the variable will be 0. +.It ICONV_GET_TRANSLITERATE +Determines if transliteration is enabled. +The answer is stored in +.Fa argument , +which is of +.Ft int * . +It will be set to 1 if this feature is enabled or set to 0 otherwise. +.It ICONV_SET_TRANSLITERATE +Enables transliteration if +.Fa argument , +which is of +.Ft int * +set to 1 or disables it if +.Fa argument +is set to 0. +.It ICONV_GET_DISCARD_ILSEQ +Determines if illegal sequences are discarded or not. +The answer is stored in +.Fa argument , +which is of +.Ft int * . +It will be set to 1 if this feature is enabled or set to 0 otherwise. +.It ICONV_SET_DISCARD_ILSEQ +Sets whether illegal sequences are discarded or not. +.Fa argument , +which is of +.Ft int * +set to 1 or disables it if +.Fa argument +is set to 0. +.It ICONV_SET_HOOKS +Sets callback functions, which will be called back after successful +conversions. +The callback functions are stored in a +.Ft struct iconv_hooks +variable, which is passed to +.Nm +via +.Fa argument +by its address. +.\" XXX: fallbacks are unimplemented and trying to set them will always +.\" return EOPNOTSUPP but definitions are provided for source-level +.\" compatibility. +.\".It ICONV_SET_FALLBACKS +.\"Sets callback functions, which will be called back after failed +.\"conversions. +.\"The callback functions are stored in a +.\".Ft struct iconv_fallbacks +.\"variable, which is passed to +.\".Nm +.\"via +.\".Fa argument +.\"by its address. +.Sh RETURN VALUES +Upon successful completion +.Fn iconvctl , +returns 0. +Otherwise, \-1 is returned and errno is set to +specify the kind of error. +.Sh ERRORS +The +.Fn iconvctl +function may cause an error in the following cases: +.Bl -tag -width Er +.It Bq Er EINVAL +Unknown or unimplemented operation. +.It Bq Er EBADF +The conversion descriptor specified by +.Fa cd +is invalid. +.Sh SEE ALSO +.Xr iconv 1 , +.Xr iconv 3 +.Sh STANDARDS +The +.Nm +facility is a non-standard extension, which appeared in +the GNU implementation and was adopted in +.Fx 9 +for compatibility's sake. +.Sh BUGS +Transliteration is enabled in this implementation by default, so it +is impossible by design to turn it off. +Accordingly, trying to turn it off will always fail and \-1 will be +returned. +Getting the transliteration state will always succeed and indicate +that it is turned on, though. +.Sh AUTHORS +This manual page was written by +.An Gabor Kovesdan Aq gabor@FreeBSD.org . diff --git a/lib/libc/iconv/iconvlist.3 b/lib/libc/iconv/iconvlist.3 new file mode 100644 index 0000000..e3fc43c --- /dev/null +++ b/lib/libc/iconv/iconvlist.3 @@ -0,0 +1,93 @@ +.\" Copyright (c) 2009 Gabor Kovesdan <gabor@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. +.\" +.\" Portions of this text are reprinted and reproduced in electronic form +.\" from IEEE Std 1003.1, 2004 Edition, Standard for Information Technology -- +.\" Portable Operating System Interface (POSIX), The Open Group Base +.\" Specifications Issue 6, Copyright (C) 2001-2004 by the Institute of +.\" Electrical and Electronics Engineers, Inc and The Open Group. In the +.\" event of any discrepancy between this version and the original IEEE and +.\" The Open Group Standard, the original IEEE and The Open Group Standard is +.\" the referee document. The original Standard can be obtained online at +.\" http://www.opengroup.org/unix/online.html. +.\" +.\" $FreeBSD$ +.\" +.Dd October 20, 2009 +.Dt ICONVLIST 3 +.Os +.Sh NAME +.Nm iconvlist +.Nd retrieving a list of character encodings supported by +.Xr iconv 3 +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In iconv.h +.Ft void +.Fo iconvlist "char ***names" "size_t count" "bool paired" +.Fa "int \*[lp]*do_one\*[rp]\*[lp]unsigned int *count, const char * const *names, void *arg\*[rp]" +.Fa "void *arg" +.Fc +.Sh DESCRIPTION +The +.Fn iconvlist +function obtains a list of character encodings that are supported by the +.Xr iconv 3 +call. +The +.Fn do_one +callback function will be called, where the +.Fa count +argument will be set to the number of the encoding names found, the +.Fa names +argument will be the list of the supported encoding names and the +.Fa arg +argument will be the \"outer\" +.Fa arg +argument of the +.Fn iconvlist +function. +This argument can be used to interchange custom data between the caller of +.Fn iconvlist +and the callback function. +.Pp +If an error occurs, +.Fa names +will be NULL when calling +.Fn do_one . +.Sh SEE ALSO +.Xr iconv 3 , +.Xr __iconv_get_list 3 , +.Xr __iconv_free_list 3 +.Sh STANDARDS +The +.Nm +function is a non-standard extension, which appeared in +the GNU implementation and was adopted in +.Fx 9 +for compatibility's sake. +.Sh AUTHORS +This manual page was written by +.An Gabor Kovesdan Aq gabor@FreeBSD.org . diff --git a/lib/libc/include/compat.h b/lib/libc/include/compat.h index 13c1d20..7694540 100644 --- a/lib/libc/include/compat.h +++ b/lib/libc/include/compat.h @@ -36,7 +36,7 @@ #define __LIBC_COMPAT_H__ #define __sym_compat(sym,impl,verid) \ - .symver impl , sym @ verid + .symver impl, sym@verid __sym_compat(__semctl, freebsd7___semctl, FBSD_1.0); __sym_compat(msgctl, freebsd7_msgctl, FBSD_1.0); diff --git a/lib/libc/include/libc_private.h b/lib/libc/include/libc_private.h index cb0b407..a4737fe 100644 --- a/lib/libc/include/libc_private.h +++ b/lib/libc/include/libc_private.h @@ -129,6 +129,8 @@ typedef enum { PJT_TESTCANCEL, PJT_CLEANUP_POP_IMP, PJT_CLEANUP_PUSH_IMP, + PJT_CANCEL_ENTER, + PJT_CANCEL_LEAVE, PJT_MAX } pjt_index_t; @@ -213,4 +215,11 @@ extern int __sys_fcntl(int, int, ...); /* execve() with PATH processing to implement posix_spawnp() */ int _execvpe(const char *, char * const *, char * const *); +int _elf_aux_info(int aux, void *buf, int buflen); +struct dl_phdr_info; +int __elf_phdr_match_addr(struct dl_phdr_info *, void *); + +void _pthread_cancel_enter(int); +void _pthread_cancel_leave(int); + #endif /* _LIBC_PRIVATE_H_ */ diff --git a/lib/libc/include/namespace.h b/lib/libc/include/namespace.h index 6ba8bab..1e00030 100644 --- a/lib/libc/include/namespace.h +++ b/lib/libc/include/namespace.h @@ -137,6 +137,7 @@ #define pthread_getprio _pthread_getprio #define pthread_getschedparam _pthread_getschedparam #define pthread_getspecific _pthread_getspecific +#define pthread_getthreadid_np _pthread_getthreadid_np #define pthread_join _pthread_join #define pthread_key_create _pthread_key_create #define pthread_key_delete _pthread_key_delete diff --git a/lib/libc/include/un-namespace.h b/lib/libc/include/un-namespace.h index 00f0df2..9c9ce97 100644 --- a/lib/libc/include/un-namespace.h +++ b/lib/libc/include/un-namespace.h @@ -118,6 +118,7 @@ #undef pthread_getprio #undef pthread_getschedparam #undef pthread_getspecific +#undef pthread_getthreadid_np #undef pthread_join #undef pthread_key_create #undef pthread_key_delete diff --git a/lib/libc/locale/Makefile.inc b/lib/libc/locale/Makefile.inc index 074c4d9..8fff0589 100644 --- a/lib/libc/locale/Makefile.inc +++ b/lib/libc/locale/Makefile.inc @@ -2,7 +2,7 @@ # $FreeBSD$ # locale sources -.PATH: ${.CURDIR}/${MACHINE_ARCH}/locale ${.CURDIR}/locale +.PATH: ${.CURDIR}/${LIBC_ARCH}/locale ${.CURDIR}/locale SRCS+= ascii.c big5.c btowc.c collate.c collcmp.c euc.c fix_grouping.c \ gb18030.c gb2312.c gbk.c isctype.c iswctype.c \ diff --git a/lib/libc/locale/isalnum.3 b/lib/libc/locale/isalnum.3 index 624a6e2..038c5cf 100644 --- a/lib/libc/locale/isalnum.3 +++ b/lib/libc/locale/isalnum.3 @@ -59,7 +59,6 @@ or the value of .Pp In the ASCII character set, this includes the following characters (with their numeric values shown in octal): -.Pp .Bl -column \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ .It "\&060\ ``0'' \t061\ ``1'' \t062\ ``2'' \t063\ ``3'' \t064\ ``4''" .It "\&065\ ``5'' \t066\ ``6'' \t067\ ``7'' \t070\ ``8'' \t071\ ``9''" diff --git a/lib/libc/locale/isalpha.3 b/lib/libc/locale/isalpha.3 index 0bd3cda..689b6cd 100644 --- a/lib/libc/locale/isalpha.3 +++ b/lib/libc/locale/isalpha.3 @@ -59,7 +59,6 @@ or the value of .Pp In the ASCII character set, this includes the following characters (with their numeric values shown in octal): -.Pp .Bl -column \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ \&000_``0''__ .It "\&101\ ``A'' \t102\ ``B'' \t103\ ``C'' \t104\ ``D'' \t105\ ``E''" .It "\&106\ ``F'' \t107\ ``G'' \t110\ ``H'' \t111\ ``I'' \t112\ ``J''" diff --git a/lib/libc/locale/isblank.3 b/lib/libc/locale/isblank.3 index 6734dcc..2668e93 100644 --- a/lib/libc/locale/isblank.3 +++ b/lib/libc/locale/isblank.3 @@ -45,9 +45,8 @@ The .Fn isblank function tests for a space or tab character. For any locale, this includes the following standard characters: -.Pp -.Bl -column \&`\et''___ \&``\et''___ -.It "\&``\et''\t`` ''" +.Bl -column XXXX +.It Do \et Dc Ta Dq " " .El .Pp In the "C" locale, a successful diff --git a/lib/libc/locale/isgraph.3 b/lib/libc/locale/isgraph.3 index 5e06e2e..ec304d0 100644 --- a/lib/libc/locale/isgraph.3 +++ b/lib/libc/locale/isgraph.3 @@ -48,7 +48,7 @@ The .Fn isgraph function tests for any printing character except space -.Pq Ql "\ " +.Pq Ql "\~" and other locale-specific space-like characters. The value of the argument must be representable as an diff --git a/lib/libc/locale/localeconv.3 b/lib/libc/locale/localeconv.3 index e03515e..c4b5746 100644 --- a/lib/libc/locale/localeconv.3 +++ b/lib/libc/locale/localeconv.3 @@ -80,7 +80,6 @@ struct lconv { .Ed .Pp The individual fields have the following meanings: -.Pp .Bl -tag -width mon_decimal_point .It Va decimal_point The decimal point character, except for currency values, diff --git a/lib/libc/locale/setlocale.3 b/lib/libc/locale/setlocale.3 index 8be6730..e0d06e8 100644 --- a/lib/libc/locale/setlocale.3 +++ b/lib/libc/locale/setlocale.3 @@ -57,7 +57,6 @@ The .Fn setlocale function recognizes several categories of routines. These are the categories and the sets of routines they select: -.Pp .Bl -tag -width LC_MONETARY .It Dv LC_ALL Set the entire locale generically. @@ -103,11 +102,11 @@ function. .Pp Only three locales are defined by default, the empty string -.Li "\&""\|"" +.Li \&"\|" which denotes the native environment, and the -.Li "\&""C"" +.Li \&"C" and -.Li "\&""POSIX"" +.Li \&"POSIX" locales, which denote the C language environment. A .Fa locale @@ -117,7 +116,7 @@ causes .Fn setlocale to return the current locale. By default, C programs start in the -.Li "\&""C"" +.Li \&"C" locale. The only function in the library that sets the locale is .Fn setlocale ; diff --git a/lib/libc/locale/tolower.3 b/lib/libc/locale/tolower.3 index fce37fd..a5cb819 100644 --- a/lib/libc/locale/tolower.3 +++ b/lib/libc/locale/tolower.3 @@ -32,7 +32,7 @@ .\" @(#)tolower.3 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd July 17, 2005 +.Dd July 25, 2010 .Dt TOLOWER 3 .Os .Sh NAME @@ -57,7 +57,7 @@ or the value of 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. +one; otherwise, the argument is returned unchanged. .Sh COMPATIBILITY The .Bx 4.4 diff --git a/lib/libc/locale/toupper.3 b/lib/libc/locale/toupper.3 index 3a3c7f8..0fd3cbb 100644 --- a/lib/libc/locale/toupper.3 +++ b/lib/libc/locale/toupper.3 @@ -32,7 +32,7 @@ .\" @(#)toupper.3 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd July 17, 2005 +.Dd July 25, 2010 .Dt TOUPPER 3 .Os .Sh NAME @@ -57,7 +57,7 @@ or the value of 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. +one; otherwise, the argument is returned unchanged. .Sh COMPATIBILITY The .Bx 4.4 diff --git a/lib/libc/mips/Makefile.inc b/lib/libc/mips/Makefile.inc index 2ae88d8..a02ca01 100644 --- a/lib/libc/mips/Makefile.inc +++ b/lib/libc/mips/Makefile.inc @@ -1,8 +1,6 @@ # $NetBSD: Makefile.inc,v 1.7 2005/09/17 11:49:39 tsutsui Exp $ # $FreeBSD$ -SOFTFLOAT_BITS=32 - CFLAGS+=-DSOFTFLOAT MDSRCS+= machdep_ldisd.c diff --git a/lib/libc/mips/SYS.h b/lib/libc/mips/SYS.h index c4aad44..10205b8 100644 --- a/lib/libc/mips/SYS.h +++ b/lib/libc/mips/SYS.h @@ -1,4 +1,4 @@ -/* $NetBSD: SYS.h,v 1.18 2003/10/29 12:28:33 pooka Exp $ */ +/* $NetBSD: SYS.h,v 1.19 2009/12/14 01:07:41 matt Exp $ */ /* $FreeBSD$ */ /*- @@ -79,14 +79,22 @@ */ #ifdef __ABICALLS__ .abicalls -# define PIC_PROLOGUE(x,sr) .set noreorder; .cpload sr; .set reorder -# define PIC_CALL(l,sr) la sr, _C_LABEL(l); jr sr +# 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,sr) -# define PIC_CALL(l,sr) j _C_LABEL(l) -#endif +# define PIC_PROLOGUE(x) +# define PIC_TAILCALL(l) j _C_LABEL(l) +# define PIC_RETURN() j ra +#endif /* __ABICALLS__ */ -# define SYSTRAP(x) li v0, SYS_ ## x; syscall; +# define SYSTRAP(x) li v0,SYS_ ## x; syscall; /* * Do a syscall that cannot fail (sync, get{p,u,g,eu,eg)id) @@ -106,7 +114,7 @@ */ #define PSEUDO_NOERROR(x) \ LEAF(__sys_ ## x); \ - .weak _C_LABEL(x); \ + .weak _C_LABEL(x); \ _C_LABEL(x) = _C_LABEL(__CONCAT(__sys_,x)); \ .weak _C_LABEL(__CONCAT(_,x)); \ _C_LABEL(__CONCAT(_,x)) = _C_LABEL(__CONCAT(__sys_,x)); \ @@ -116,14 +124,14 @@ LEAF(__sys_ ## x); \ #define PSEUDO(x) \ LEAF(__sys_ ## x); \ - .weak _C_LABEL(x); \ + .weak _C_LABEL(x); \ _C_LABEL(x) = _C_LABEL(__CONCAT(__sys_,x)); \ .weak _C_LABEL(__CONCAT(_,x)); \ _C_LABEL(__CONCAT(_,x)) = _C_LABEL(__CONCAT(__sys_,x)); \ - PIC_PROLOGUE(x,t9); \ + PIC_PROLOGUE(__sys_ ## x); \ SYSTRAP(x); \ bne a3,zero,err; \ - j ra; \ + PIC_RETURN(); \ err: \ - PIC_CALL(__cerror,t9); \ - END(__sys_ ## x) + PIC_TAILCALL(__cerror); \ +END(__sys_ ## x) diff --git a/lib/libc/mips/Symbol.map b/lib/libc/mips/Symbol.map index 3f24c11..b478551 100644 --- a/lib/libc/mips/Symbol.map +++ b/lib/libc/mips/Symbol.map @@ -24,13 +24,9 @@ FBSD_1.0 { sigsetjmp; siglongjmp; htonl; - __htonl; htons; - __htons; ntohl; - __ntohl; ntohs; - __ntohs; vfork; brk; cerror; /* XXX - Should this be .cerror (see sys/cerror.S)? */ diff --git a/lib/libc/mips/gen/Makefile.inc b/lib/libc/mips/gen/Makefile.inc index 2fa20b0..1fafb01 100644 --- a/lib/libc/mips/gen/Makefile.inc +++ b/lib/libc/mips/gen/Makefile.inc @@ -6,4 +6,4 @@ SRCS+= infinity.c fabs.c ldexp.c modf.c # SRCS+= flt_rounds.c fpgetmask.c fpgetround.c fpgetsticky.c fpsetmask.c \ # fpsetround.c fpsetsticky.c -SRCS+= _set_tp.c _setjmp.S makecontext.c setjmp.S signalcontext.c sigsetjmp.S +SRCS+= _ctx_start.S _set_tp.c _setjmp.S makecontext.c setjmp.S signalcontext.c sigsetjmp.S diff --git a/lib/libc/i386/gen/ldexp.c b/lib/libc/mips/gen/_ctx_start.S index 88bbb04..5d754a9 100644 --- a/lib/libc/i386/gen/ldexp.c +++ b/lib/libc/mips/gen/_ctx_start.S @@ -1,9 +1,6 @@ /*- - * Copyright (c) 1990, 1993 - * The Regents of the University of California. All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * Sean Eric Fagan. + * Copyright (c) 2010 Juli Mallett. + * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -13,14 +10,11 @@ * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) @@ -30,35 +24,18 @@ * SUCH DAMAGE. */ -#if defined(LIBC_SCCS) && !defined(lint) -static char sccsid[] = "@(#)ldexp.c 8.1 (Berkeley) 6/4/93"; -#endif /* LIBC_SCCS and not lint */ -#include <sys/cdefs.h> +#include <machine/asm.h> __FBSDID("$FreeBSD$"); -#include <math.h> - /* - * ldexp(value, exp): return value * (2 ** exp). - * - * Written by Sean Eric Fagan (sef@kithrup.COM) - * Sun Mar 11 20:27:09 PST 1990 + * XXX gp? */ +ENTRY(_ctx_start) + jalr t9 -/* - * We do the conversion in C to let gcc optimize it away, if possible. - */ -double -ldexp (double value, int exp) -{ - double temp, texp, temp2; - texp = exp; -#ifdef __GNUC__ - __asm ("fscale " - : "=u" (temp2), "=t" (temp) - : "0" (texp), "1" (value)); -#else -#error unknown asm -#endif - return (temp); -} + move a0, s0 + PTR_LA t9, _ctx_done + jalr t9 + + break 0 +END(_ctx_start) diff --git a/lib/libc/mips/gen/_setjmp.S b/lib/libc/mips/gen/_setjmp.S index 596c712..3918407 100644 --- a/lib/libc/mips/gen/_setjmp.S +++ b/lib/libc/mips/gen/_setjmp.S @@ -1,4 +1,4 @@ -/* $NetBSD: _setjmp.S,v 1.20 2005/10/07 17:16:40 tsutsui Exp $ */ +/* $NetBSD: _setjmp.S,v 1.20.34.5 2010/02/03 23:46:47 matt Exp $ */ /*- * Copyright (c) 1991, 1993 @@ -36,14 +36,15 @@ __FBSDID("$FreeBSD$"); #include <machine/regnum.h> -#if defined(LIBC_SCCS) && !defined(lint) - ASMSTR("from: @(#)_setjmp.s 8.1 (Berkeley) 6/4/93") - ASMSTR("$NetBSD: _setjmp.S,v 1.20 2005/10/07 17:16:40 tsutsui Exp $") -#endif /* LIBC_SCCS and not lint */ +#include "SYS.h" -#ifdef __ABICALLS__ - .abicalls +#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.20.34.5 2010/02/03 23:46:47 matt Exp $") #endif +#endif /* LIBC_SCCS and not lint */ /* * C library -- _setjmp, _longjmp @@ -56,62 +57,70 @@ __FBSDID("$FreeBSD$"); * The previous signal state is NOT restored. */ + .set noreorder LEAF(_setjmp) -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - subu sp, sp, CALLFRAME_SIZ # allocate stack frame - .cprestore 16 + REG_PROLOGUE + REG_LI v0, _JB_MAGIC__SETJMP + REG_S v0, (_JB_MAGIC * SZREG)(a0) + REG_S ra, (_JB_REG_RA * SZREG)(a0) + REG_S s0, (_JB_REG_S0 * SZREG)(a0) + REG_S s1, (_JB_REG_S1 * SZREG)(a0) + REG_S s2, (_JB_REG_S2 * SZREG)(a0) + REG_S s3, (_JB_REG_S3 * SZREG)(a0) + REG_S s4, (_JB_REG_S4 * SZREG)(a0) + REG_S s5, (_JB_REG_S5 * SZREG)(a0) + REG_S s6, (_JB_REG_S6 * SZREG)(a0) + REG_S s7, (_JB_REG_S7 * SZREG)(a0) + REG_S s8, (_JB_REG_S8 * SZREG)(a0) +#if defined(__mips_n32) || defined(__mips_n64) + REG_S gp, (_JB_REG_GP * SZREG)(a0) # newabi gp is callee-saved #endif - li v0, _JB_MAGIC__SETJMP - sw v0, (_JB_MAGIC * SZREG)(a0) - sw ra, (_JB_REG_RA * SZREG)(a0) - sw s0, (_JB_REG_S0 * SZREG)(a0) - sw s1, (_JB_REG_S1 * SZREG)(a0) - sw s2, (_JB_REG_S2 * SZREG)(a0) - sw s3, (_JB_REG_S3 * SZREG)(a0) - sw s4, (_JB_REG_S4 * SZREG)(a0) - sw s5, (_JB_REG_S5 * SZREG)(a0) - sw s6, (_JB_REG_S6 * SZREG)(a0) - sw s7, (_JB_REG_S7 * SZREG)(a0) - sw s8, (_JB_REG_S8 * SZREG)(a0) -#ifdef __ABICALLS__ - addu sp, sp, CALLFRAME_SIZ # un-allocate the stack frame -#endif - sw sp, (_JB_REG_SP * SZREG)(a0) + REG_S sp, (_JB_REG_SP * SZREG)(a0) + REG_EPILOGUE + j ra move v0, zero END(_setjmp) LEAF(_longjmp) -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - subu sp, sp, CALLFRAME_SIZ # allocate stack frame - .cprestore 16 -#endif - lw v0, (_JB_MAGIC * SZREG)(a0) - lw ra, (_JB_REG_RA * SZREG)(a0) - li t0, _JB_MAGIC__SETJMP - bne v0, t0, botch # jump if error - lw s0, (_JB_REG_S0 * SZREG)(a0) - lw s1, (_JB_REG_S1 * SZREG)(a0) - lw s2, (_JB_REG_S2 * SZREG)(a0) - lw s3, (_JB_REG_S3 * SZREG)(a0) - lw s4, (_JB_REG_S4 * SZREG)(a0) - lw s5, (_JB_REG_S5 * SZREG)(a0) - lw s6, (_JB_REG_S6 * SZREG)(a0) - lw s7, (_JB_REG_S7 * SZREG)(a0) - lw sp, (_JB_REG_SP * SZREG)(a0) - lw s8, (_JB_REG_S8 * SZREG)(a0) + PIC_PROLOGUE(_longjmp) + PTR_SUBU sp, sp, CALLFRAME_SIZ + SAVE_GP(CALLFRAME_GP) + + REG_PROLOGUE + REG_L v0, (_JB_MAGIC * SZREG)(a0) # get magic number + REG_L ra, (_JB_REG_RA * SZREG)(a0) + REG_LI t0, _JB_MAGIC__SETJMP + bne v0, t0, botch # jump if error + PTR_ADDU sp, sp, CALLFRAME_SIZ # does not matter, sanity + REG_L s0, (_JB_REG_S0 * SZREG)(a0) + REG_L s1, (_JB_REG_S1 * SZREG)(a0) + REG_L s2, (_JB_REG_S2 * SZREG)(a0) + REG_L s3, (_JB_REG_S3 * SZREG)(a0) + REG_L s4, (_JB_REG_S4 * SZREG)(a0) + REG_L s5, (_JB_REG_S5 * SZREG)(a0) + REG_L s6, (_JB_REG_S6 * SZREG)(a0) + REG_L s7, (_JB_REG_S7 * SZREG)(a0) +#if defined(__mips_n32) || defined(__mips_n64) + REG_L gp, (_JB_REG_GP * SZREG)(a0) +#endif + REG_L sp, (_JB_REG_SP * SZREG)(a0) + REG_L s8, (_JB_REG_S8 * SZREG)(a0) + REG_EPILOGUE + move v0, a1 # get return value in 1st arg j ra - move v0, a1 + nop botch: - jal _C_LABEL(longjmperror) - nop - jal _C_LABEL(abort) + /* + * We know we aren't returning so we don't care about restoring + * our caller's GP. + */ + PTR_LA t9, _C_LABEL(longjmperror) + jalr t9 nop + + PIC_TAILCALL(abort) END(_longjmp) diff --git a/lib/libc/mips/gen/makecontext.c b/lib/libc/mips/gen/makecontext.c index 01d88bf..f2a826e 100644 --- a/lib/libc/mips/gen/makecontext.c +++ b/lib/libc/mips/gen/makecontext.c @@ -1,4 +1,4 @@ -/* $NetBSD: makecontext.c,v 1.3 2003/01/19 08:53:36 matt Exp $ */ +/* $NetBSD: makecontext.c,v 1.5 2009/12/14 01:07:42 matt Exp $ */ /*- * Copyright (c) 2001 The NetBSD Foundation, Inc. @@ -15,13 +15,6 @@ * 2. Redistributions in binary form must reproduce 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 @@ -39,48 +32,92 @@ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #if defined(LIBC_SCCS) && !defined(lint) -__RCSID("$NetBSD: makecontext.c,v 1.3 2003/01/19 08:53:36 matt Exp $"); +__RCSID("$NetBSD: makecontext.c,v 1.5 2009/12/14 01:07:42 matt Exp $"); #endif -#include <sys/types.h> -#include <ucontext.h> +#include <sys/param.h> +#include <machine/regnum.h> + #include <stdarg.h> +#include <stdlib.h> +#include <unistd.h> +#include <stdio.h> +#include <ucontext.h> + +__weak_reference(__makecontext, makecontext); + +void _ctx_done(ucontext_t *); +void _ctx_start(void); void -makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...) +__makecontext(ucontext_t *ucp, void (*func)(void), int argc, ...) { - /* XXXMIPS: Implement me */ -#if 0 - __greg_t *gr = ucp->uc_mcontext.__gregs; - uintptr_t *sp; + mcontext_t *mc; + register_t *sp; int i; va_list ap; - void __resumecontext(void); + /* + * XXX/juli + * We need an mc_len or mc_flags like other architectures + * so that we can mark a context as invalid. Store it in + * mc->mc_regs[ZERO] perhaps? + */ + if (argc < 0 || argc > 6 || ucp == NULL || + ucp->uc_stack.ss_sp == NULL || + ucp->uc_stack.ss_size < MINSIGSTKSZ) + return; + mc = &ucp->uc_mcontext; - /* LINTED uintptr_t is safe */ - sp = (uintptr_t *) + sp = (register_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 = (uintptr_t *) - ((uintptr_t)sp & ~0x7); /* Align on double-word boundary. */ + sp = (register_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 = (register_t *) + ((uintptr_t)sp & ~0xf); /* Align on quad-word boundary. */ +#endif - gr[_REG_SP] = (__greg_t)sp; - gr[_REG_RA] = (__greg_t)__resumecontext; - gr[_REG_T9] = (__greg_t)func; /* required for .abicalls */ - gr[_REG_EPC] = (__greg_t)func; + mc->mc_regs[SP] = (intptr_t)sp; + mc->mc_regs[S0] = (intptr_t)ucp; + mc->mc_regs[T9] = (intptr_t)func; + mc->mc_pc = (intptr_t)_ctx_start; /* 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 uintptr_t is safe */ - gr[_REG_A0 + i] = va_arg(ap, uintptr_t); + /* LINTED register_t is safe */ + mc->mc_regs[A0 + i] = va_arg(ap, register_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 register_t is safe */ + mc->mc_regs[A0 + i] = va_arg(ap, register_t); /* Pass remaining arguments on the stack above the $a0-3 gap. */ - for (sp += 4; i < argc; i++) +#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, uintptr_t); + *sp++ = va_arg(ap, register_t); va_end(ap); -#endif +} + +void +_ctx_done(ucontext_t *ucp) +{ + + if (ucp->uc_link == NULL) + exit(0); + else { + setcontext((const ucontext_t *)ucp->uc_link); + abort(); + } } diff --git a/lib/libc/mips/gen/modf.c b/lib/libc/mips/gen/modf.c index 347090c..cb5aeac 100644 --- a/lib/libc/mips/gen/modf.c +++ b/lib/libc/mips/gen/modf.c @@ -86,7 +86,7 @@ modf(val, iptr) * 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 the fractional part is the part with the rest of the + * 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 diff --git a/lib/libc/mips/gen/setjmp.S b/lib/libc/mips/gen/setjmp.S index 2abc57b..deeb892 100644 --- a/lib/libc/mips/gen/setjmp.S +++ b/lib/libc/mips/gen/setjmp.S @@ -41,6 +41,8 @@ __FBSDID("$FreeBSD$"); ASMSTR("$NetBSD: setjmp.S,v 1.17 2005/09/17 11:49:39 tsutsui Exp $") #endif /* LIBC_SCCS and not lint */ +#include "SYS.h" + #ifdef __ABICALLS__ .abicalls #endif @@ -61,100 +63,102 @@ __FBSDID("$FreeBSD$"); NESTED(setjmp, SETJMP_FRAME_SIZE, ra) .mask 0x80000000, (CALLFRAME_RA - CALLFRAME_SIZ) - .set noreorder -#ifdef __ABICALLS__ - .cpload t9 -#endif - subu sp, sp, SETJMP_FRAME_SIZE # allocate stack frame -#ifdef __ABICALLS__ - .cprestore 16 -#endif - sw ra, CALLFRAME_RA(sp) # save RA - sw a0, CALLFRAME_SIZ(sp) # store env + 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 a0, CALLFRAME_SIZ(sp) # store env /* Get the signal mask. */ - addu a2, a0, _JB_SIGMASK * SZREG # &oenv + PTR_ADDU a2, a0, _JB_SIGMASK * SZREG # &oenv li a0, 1 # SIG_SETBLOCK move a1, zero # &env == 0 - la t9, _C_LABEL(sigprocmask) # get current signal mask - jal t9 - nop - - lw a0, CALLFRAME_SIZ(sp) # restore env pointer - lw ra, CALLFRAME_RA(sp) # restore RA - addu sp, sp, SETJMP_FRAME_SIZE # pop stack frame - - li v0, _JB_MAGIC_SETJMP - sw v0, (_JB_MAGIC * SZREG)(a0) - sw ra, (_JB_REG_RA * SZREG)(a0) - sw s0, (_JB_REG_S0 * SZREG)(a0) - sw s1, (_JB_REG_S1 * SZREG)(a0) - sw s2, (_JB_REG_S2 * SZREG)(a0) - sw s3, (_JB_REG_S3 * SZREG)(a0) - sw s4, (_JB_REG_S4 * SZREG)(a0) - sw s5, (_JB_REG_S5 * SZREG)(a0) - sw s6, (_JB_REG_S6 * SZREG)(a0) - sw s7, (_JB_REG_S7 * SZREG)(a0) - sw sp, (_JB_REG_SP * SZREG)(a0) - sw s8, (_JB_REG_S8 * SZREG)(a0) + PTR_LA t9, _C_LABEL(sigprocmask) # get current signal mask + jalr t9 + + RESTORE_GP64 + REG_L a0, CALLFRAME_SIZ(sp) # restore env pointer + REG_L ra, CALLFRAME_RA(sp) # restore RA + PTR_ADDU sp, sp, SETJMP_FRAME_SIZE # pop stack frame + + REG_LI v0, _JB_MAGIC_SETJMP + REG_S v0, (_JB_MAGIC * SZREG)(a0) + REG_S ra, (_JB_REG_RA * SZREG)(a0) + REG_S s0, (_JB_REG_S0 * SZREG)(a0) + REG_S s1, (_JB_REG_S1 * SZREG)(a0) + REG_S s2, (_JB_REG_S2 * SZREG)(a0) + REG_S s3, (_JB_REG_S3 * SZREG)(a0) + REG_S s4, (_JB_REG_S4 * SZREG)(a0) + REG_S s5, (_JB_REG_S5 * SZREG)(a0) + REG_S s6, (_JB_REG_S6 * SZREG)(a0) + REG_S s7, (_JB_REG_S7 * SZREG)(a0) + REG_S sp, (_JB_REG_SP * SZREG)(a0) + REG_S s8, (_JB_REG_S8 * SZREG)(a0) +#if defined(__mips_n32) || defined(__mips_n64) + REG_S gp, (_JB_REG_GP * SZREG)(a0) +#endif move v0, zero - j ra + jr ra END(setjmp) #define LONGJMP_FRAME_SIZE (CALLFRAME_SIZ + (SZREG * 2)) NESTED(longjmp, LONGJMP_FRAME_SIZE, ra) .mask 0x80000000, (CALLFRAME_RA - CALLFRAME_SIZ) - .set noreorder -#ifdef __ABICALLS__ - .cpload t9 -#endif - subu sp, sp, LONGJMP_FRAME_SIZE # allocate stack frame -#ifdef __ABICALLS__ - .cprestore 16 -#endif - sw ra, CALLFRAME_RA(sp) # save RA - lw v0, (_JB_MAGIC * SZREG)(a0) - li t0, _JB_MAGIC_SETJMP + PIC_PROLOGUE(longjmp) + PTR_SUBU sp, sp, LONGJMP_FRAME_SIZE # allocate stack frame + SAVE_GP(CALLFRAME_GP) + + REG_S ra, CALLFRAME_RA(sp) # save RA + REG_L v0, (_JB_MAGIC * SZREG)(a0) + REG_LI t0, _JB_MAGIC_SETJMP bne v0, t0, botch # jump if error nop - sw a0, CALLFRAME_SIZ(sp) # save env - sw a1, (CALLFRAME_SIZ + SZREG)(sp) # save return value + REG_S a0, CALLFRAME_SIZ(sp) # save env + REG_S a1, (CALLFRAME_SIZ + SZREG)(sp) # save return value # set sigmask - addu a1, a0, _JB_SIGMASK * SZREG # &set + PTR_ADDU a1, a0, _JB_SIGMASK * SZREG # &set move a2, zero # &oset == NULL li a0, 3 # SIG_SETMASK - la t9,_C_LABEL(sigprocmask) # set current signal mask + PTR_LA t9,_C_LABEL(sigprocmask) # set current signal mask jal t9 nop - lw a0, CALLFRAME_SIZ(sp) # restore env - lw a1, (CALLFRAME_SIZ + SZREG)(sp) # restore return value - - lw ra, (_JB_REG_RA * SZREG)(a0) - lw s0, (_JB_REG_S0 * SZREG)(a0) - lw s1, (_JB_REG_S1 * SZREG)(a0) - lw s2, (_JB_REG_S2 * SZREG)(a0) - lw s3, (_JB_REG_S3 * SZREG)(a0) - lw s4, (_JB_REG_S4 * SZREG)(a0) - lw s5, (_JB_REG_S5 * SZREG)(a0) - lw s6, (_JB_REG_S6 * SZREG)(a0) - lw s7, (_JB_REG_S7 * SZREG)(a0) - lw sp, (_JB_REG_SP * SZREG)(a0) - lw s8, (_JB_REG_S8 * SZREG)(a0) + REG_L a0, CALLFRAME_SIZ(sp) # restore env + REG_L a1, (CALLFRAME_SIZ + SZREG)(sp) # restore return value + + REG_L ra, (_JB_REG_RA * SZREG)(a0) + REG_L s0, (_JB_REG_S0 * SZREG)(a0) + REG_L s1, (_JB_REG_S1 * SZREG)(a0) + REG_L s2, (_JB_REG_S2 * SZREG)(a0) + REG_L s3, (_JB_REG_S3 * SZREG)(a0) + REG_L s4, (_JB_REG_S4 * SZREG)(a0) + REG_L s5, (_JB_REG_S5 * SZREG)(a0) + REG_L s6, (_JB_REG_S6 * SZREG)(a0) + REG_L s7, (_JB_REG_S7 * SZREG)(a0) + REG_L sp, (_JB_REG_SP * SZREG)(a0) + REG_L s8, (_JB_REG_S8 * SZREG)(a0) +#if defined(__mips_n32) || defined(__mips_n64) + REG_L gp, (_JB_REG_GP * SZREG)(a0) +#endif + move v0, a1 j ra nop botch: - la t9, _C_LABEL(longjmperror) - jal t9 + /* + * We know we aren't returning so we don't care about restoring + * our caller's GP. + */ + PTR_LA t9, _C_LABEL(longjmperror) + jalr t9 nop - la t9, _C_LABEL(abort) - jal t9 - nop + PIC_TAILCALL(abort) END(longjmp) diff --git a/lib/libc/mips/gen/sigsetjmp.S b/lib/libc/mips/gen/sigsetjmp.S index 4e86e28..7705c29 100644 --- a/lib/libc/mips/gen/sigsetjmp.S +++ b/lib/libc/mips/gen/sigsetjmp.S @@ -40,6 +40,8 @@ __FBSDID("$FreeBSD$"); ASMSTR("$NetBSD: sigsetjmp.S,v 1.8 2005/09/17 11:49:39 tsutsui Exp $") #endif /* LIBC_SCCS and not lint */ +#include "SYS.h" + #ifdef __ABICALLS__ .abicalls #endif @@ -57,30 +59,19 @@ __FBSDID("$FreeBSD$"); */ LEAF(sigsetjmp) -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - .set reorder -#endif + PIC_PROLOGUE(sigsetjmp) + bne a1, 0x0, 1f # do saving of signal mask? - la t9, _setjmp - jr t9 + PIC_TAILCALL(_setjmp) -1: la t9, setjmp - jr t9 +1: PIC_TAILCALL(setjmp) END(sigsetjmp) LEAF(siglongjmp) -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - .set reorder -#endif - lw t0, (_JB_MAGIC * SZREG)(a0) - li t1, _JB_MAGIC__SETJMP + PIC_PROLOGUE(siglongjmp) + REG_L t0, (_JB_MAGIC * SZREG)(a0) + REG_LI t1, _JB_MAGIC__SETJMP bne t0, t1, 1f # setjmp or _setjmp magic? - la t9, _longjmp - jr t9 -1: la t9, longjmp - jr t9 + PIC_TAILCALL(_longjmp) +1: PIC_TAILCALL(longjmp) END(siglongjmp) diff --git a/lib/libc/mips/string/bcmp.S b/lib/libc/mips/string/bcmp.S index 7b7fa68..ffcaeeb 100644 --- a/lib/libc/mips/string/bcmp.S +++ b/lib/libc/mips/string/bcmp.S @@ -1,4 +1,4 @@ -/* $NetBSD: bcmp.S,v 1.8 2003/08/07 16:42:16 agc Exp $ */ +/* $NetBSD: bcmp.S,v 1.9 2009/12/14 01:07:42 matt Exp $ */ /*- * Copyright (c) 1991, 1993 @@ -35,9 +35,15 @@ #include <machine/asm.h> __FBSDID("$FreeBSD$"); +#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 ASMSTR("from: @(#)bcmp.s 8.1 (Berkeley) 6/4/93") - ASMSTR("$NetBSD: bcmp.S,v 1.8 2003/08/07 16:42:16 agc Exp $") +#else + ASMSTR("$NetBSD: bcmp.S,v 1.9 2009/12/14 01:07:42 matt Exp $") +#endif #endif /* LIBC_SCCS and not lint */ #ifdef __ABICALLS__ @@ -49,86 +55,76 @@ __FBSDID("$FreeBSD$"); 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 - subu a3, zero, a1 # compute # bytes to word align address - bne v0, zero, unaligned # not possible to align addresses - and a3, a3, 3 + 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 - subu a2, a2, a3 # subtract from remaining count - move v0, v1 # init v0,v1 so unmodified bytes match -#ifdef __MIPSEB__ - lwl v0, 0(a0) # read 1, 2, or 3 bytes - lwl v1, 0(a1) -#else - lwr v0, 0(a0) # read 1, 2, or 3 bytes - lwr v1, 0(a1) -#endif - addu a1, a1, a3 - bne v0, v1, nomatch - addu a0, a0, a3 + 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 - subu a2, a2, a3 # which has to be >= (16-3) & ~3 - addu a3, a3, a0 # compute ending address + 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) - addu a0, a0, 4 - bne v0, v1, nomatch - addu a1, a1, 4 - bne a0, a3, 2b + 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 + b small # finish remainder nop unaligned: - beq a3, zero, 2f - subu a2, a2, a3 # subtract from remaining count - addu a3, a3, a0 # compute ending address + 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) - addu a0, a0, 1 - bne v0, v1, nomatch - addu a1, a1, 1 - bne a0, a3, 1b + 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 - subu a2, a2, a3 # which has to be >= (16-3) & ~3 - addu a3, a3, a0 # compute ending address + 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: -#ifdef __MIPSEB__ - lwl v0, 0(a0) # compare words a0 unaligned, a1 aligned - lwr v0, 3(a0) -#else - lwr v0, 0(a0) # compare words a0 unaligned, a1 aligned - lwl v0, 3(a0) -#endif - lw v1, 0(a1) - addu a0, a0, 4 - bne v0, v1, nomatch - addu a1, a1, 4 - bne a0, a3, 3b + 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 - addu a3, a2, a0 # compute ending address + ble a2, zero, match + PTR_ADDU a3, a2, a0 # compute ending address 1: - lbu v0, 0(a0) - lbu v1, 0(a1) - addu a0, a0, 1 - bne v0, v1, nomatch - addu a1, a1, 1 - bne a0, a3, 1b + 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 + j ra + move v0, zero nomatch: - j ra - li v0, 1 + j ra + li v0, 1 .set reorder END(bcmp) diff --git a/lib/libc/mips/string/bcopy.S b/lib/libc/mips/string/bcopy.S index 6287d06..bc227e0 100644 --- a/lib/libc/mips/string/bcopy.S +++ b/lib/libc/mips/string/bcopy.S @@ -1,4 +1,4 @@ -/* $NetBSD: bcopy.S,v 1.2 2005/12/27 11:23:53 tsutsui Exp $ */ +/* $NetBSD: bcopy.S,v 1.3 2009/12/14 00:39:00 matt Exp $ */ /* * Mach Operating System @@ -38,9 +38,15 @@ #include <machine/asm.h> __FBSDID("$FreeBSD$"); +#define _LOCORE /* XXX not really, just assembly-code source */ +#include <machine/endian.h> + #if defined(LIBC_SCCS) && !defined(lint) +#if 0 ASMSTR("from: @(#)mips_bcopy.s 2.2 CMU 18/06/93") - ASMSTR("$NetBSD: bcopy.S,v 1.2 2005/12/27 11:23:53 tsutsui Exp $") +#else + ASMSTR("$NetBSD: bcopy.S,v 1.3 2009/12/14 00:39:00 matt Exp $") +#endif #endif /* LIBC_SCCS and not lint */ #ifdef __ABICALLS__ @@ -99,71 +105,72 @@ LEAF(FUNCTION) * copy is alignable. eg if src and dest are both * on a halfword boundary. */ - andi t1,DSTREG,3 # get last 3 bits of dest - bne t1,zero,3f - andi t0,SRCREG,3 # get last 3 bits of src - bne t0,zero,5f + 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*4 bytes at a time. + * Forward aligned->aligned copy, 8 words at a time. */ - li AT,-32 - and t0,SIZEREG,AT # count truncated to multiple of 32 */ - addu a3,SRCREG,t0 # run fast loop up to this address - sltu AT,SRCREG,a3 # any work to do? - beq AT,zero,2f - subu SIZEREG,t0 +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 - lw t3,0(SRCREG) - lw v1,4(SRCREG) - lw t0,8(SRCREG) - lw t1,12(SRCREG) - addu SRCREG,32 - sw t3,0(DSTREG) - sw v1,4(DSTREG) - sw t0,8(DSTREG) - sw t1,12(DSTREG) - lw t1,-4(SRCREG) - lw t0,-8(SRCREG) - lw v1,-12(SRCREG) - lw t3,-16(SRCREG) - addu DSTREG,32 - sw t1,-4(DSTREG) - sw t0,-8(DSTREG) - sw v1,-12(DSTREG) - bne SRCREG,a3,1b - sw t3,-16(DSTREG) + 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,3 # get byte count / 4 - subu t2,SIZEREG,t2 # t2 = number of words to copy * 4 - beq t2,zero,3f - addu t0,SRCREG,t2 # stop at t0 - subu SIZEREG,SIZEREG,t2 + 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: - lw t3,0(SRCREG) - addu SRCREG,4 - sw t3,0(DSTREG) - bne SRCREG,t0,1b - addu DSTREG,4 + 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? + beq SIZEREG,zero,4f # nothing left to do? nop 1: - lb t3,0(SRCREG) - addu SRCREG,1 - sb t3,0(DSTREG) - subu SIZEREG,1 - bgtz SIZEREG,1b - addu DSTREG,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 @@ -173,96 +180,91 @@ LEAF(FUNCTION) * Copy from unaligned source to aligned dest. */ 5: # destaligned - andi t0,SIZEREG,3 # t0 = bytecount mod 4 - subu a3,SIZEREG,t0 # number of words to transfer - beq a3,zero,3b + 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 - addu a3,SRCREG,a3 # stop point + move SIZEREG,t0 # this many to do after we are done + PTR_ADDU a3,SRCREG,a3 # stop point 1: -#ifdef __MIPSEB__ - lwl t3,0(SRCREG) - lwr t3,3(SRCREG) -#else - lwr t3,0(SRCREG) - lwl t3,3(SRCREG) -#endif - addi SRCREG,4 - sw t3,0(DSTREG) - bne SRCREG,a3,1b - addi DSTREG,4 + 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 - j 3b + b 3b nop 6: # backcopy -- based on above - addu SRCREG,SIZEREG - addu DSTREG,SIZEREG - andi t1,DSTREG,3 # get last 3 bits of dest - bne t1,zero,3f - andi t0,SRCREG,3 # get last 3 bits of src - bne t0,zero,5f + 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,-32 - and t0,SIZEREG,AT # count truncated to multiple of 32 - beq t0,zero,2f # any work to do? - subu SIZEREG,t0 - subu a3,SRCREG,t0 + 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 - lw t3,-16(SRCREG) - lw v1,-12(SRCREG) - lw t0,-8(SRCREG) - lw t1,-4(SRCREG) - subu SRCREG,32 - sw t3,-16(DSTREG) - sw v1,-12(DSTREG) - sw t0,-8(DSTREG) - sw t1,-4(DSTREG) - lw t1,12(SRCREG) - lw t0,8(SRCREG) - lw v1,4(SRCREG) - lw t3,0(SRCREG) - subu DSTREG,32 - sw t1,12(DSTREG) - sw t0,8(DSTREG) - sw v1,4(DSTREG) - bne SRCREG,a3,1b - sw t3,0(DSTREG) + 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,3 # get byte count / 4 - subu t2,SIZEREG,t2 # t2 = number of words to copy * 4 - beq t2,zero,3f - subu t0,SRCREG,t2 # stop at t0 - subu SIZEREG,SIZEREG,t2 + 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: - lw t3,-4(SRCREG) - subu SRCREG,4 - sw t3,-4(DSTREG) - bne SRCREG,t0,1b - subu DSTREG,4 + 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? + beq SIZEREG,zero,4f # nothing left to do? nop 1: - lb t3,-1(SRCREG) - subu SRCREG,1 - sb t3,-1(DSTREG) - subu SIZEREG,1 - bgtz SIZEREG,1b - subu DSTREG,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 @@ -272,27 +274,22 @@ LEAF(FUNCTION) * Copy from unaligned source to aligned dest. */ 5: # destaligned - andi t0,SIZEREG,3 # t0 = bytecount mod 4 - subu a3,SIZEREG,t0 # number of words to transfer - beq a3,zero,3b + 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 - subu a3,SRCREG,a3 # stop point + move SIZEREG,t0 # this many to do after we are done + PTR_SUBU a3,SRCREG,a3 # stop point 1: -#ifdef __MIPSEB__ - lwl t3,-4(SRCREG) - lwr t3,-1(SRCREG) -#else - lwr t3,-4(SRCREG) - lwl t3,-1(SRCREG) -#endif - subu SRCREG,4 - sw t3,-4(DSTREG) - bne SRCREG,a3,1b - subu DSTREG,4 + 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 - j 3b + b 3b nop .set reorder diff --git a/lib/libc/mips/string/bzero.S b/lib/libc/mips/string/bzero.S index 9b34130..83e54ba 100644 --- a/lib/libc/mips/string/bzero.S +++ b/lib/libc/mips/string/bzero.S @@ -1,4 +1,4 @@ -/* $NetBSD: bzero.S,v 1.8 2003/08/07 16:42:16 agc Exp $ */ +/* $NetBSD: bzero.S,v 1.10 2009/12/14 02:53:52 matt Exp $ */ /*- * Copyright (c) 1991, 1993 @@ -36,10 +36,15 @@ __FBSDID("$FreeBSD$"); #if defined(LIBC_SCCS) && !defined(lint) +#if 0 ASMSTR("from: @(#)bzero.s 8.1 (Berkeley) 6/4/93") - ASMSTR("$NetBSD: bzero.S,v 1.8 2003/08/07 16:42:16 agc Exp $") +#else + ASMSTR("$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> #ifdef __ABICALLS__ .abicalls @@ -49,34 +54,30 @@ __FBSDID("$FreeBSD$"); LEAF(bzero) .set noreorder - blt a1, 12, smallclr # small amount to clear? - subu a3, zero, a0 # compute # bytes to word align address - and a3, a3, 3 - beq a3, zero, 1f # skip if word aligned - subu a1, a1, a3 # subtract from remaining count -#ifdef __MIPSEB__ - swl zero, 0(a0) # clear 1, 2, or 3 bytes to align -#else - swr zero, 0(a0) # clear 1, 2, or 3 bytes to align -#endif - addu a0, a0, a3 + 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 + PTR_SUBU a1, a1, a3 # subtract from remaining count + REG_SHI zero, 0(a0) # clear 1, 2, or 3 bytes to align + PTR_ADDU a0, a0, a3 1: - and v0, a1, 3 # compute number of words left - subu a3, a1, v0 - move a1, v0 - addu a3, a3, a0 # compute ending address + 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: - addu a0, a0, 4 # clear words - bne a0, a3, 2b # unrolling loop doesnt help - sw zero, -4(a0) # since we are limited by memory speed + 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 - addu a3, a1, a0 # compute ending address + ble a1, zero, 2f + PTR_ADDU a3, a1, a0 # compute ending address 1: - addu a0, a0, 1 # clear bytes - bne a0, a3, 1b - sb zero, -1(a0) + PTR_ADDU a0, a0, 1 # clear bytes + bne a0, a3, 1b + sb zero, -1(a0) 2: - j ra + j ra nop END(bzero) diff --git a/lib/libc/mips/string/ffs.S b/lib/libc/mips/string/ffs.S index 8df2be3..17e509c 100644 --- a/lib/libc/mips/string/ffs.S +++ b/lib/libc/mips/string/ffs.S @@ -1,4 +1,4 @@ -/* $NetBSD: ffs.S,v 1.1 2005/12/20 19:28:49 christos Exp $ */ +/* $NetBSD: ffs.S,v 1.2 2009/12/14 00:39:00 matt Exp $ */ /*- * Copyright (c) 1991, 1993 @@ -37,7 +37,7 @@ __FBSDID("$FreeBSD$"); #if defined(LIBC_SCCS) && !defined(lint) ASMSTR("from: @(#)ffs.s 8.1 (Berkeley) 6/4/93") - ASMSTR("$NetBSD: ffs.S,v 1.1 2005/12/20 19:28:49 christos Exp $") + ASMSTR("$NetBSD: ffs.S,v 1.2 2009/12/14 00:39:00 matt Exp $") #endif /* LIBC_SCCS and not lint */ #ifdef __ABICALLS__ diff --git a/lib/libc/mips/string/index.S b/lib/libc/mips/string/index.S index 055baac..d1df540 100644 --- a/lib/libc/mips/string/index.S +++ b/lib/libc/mips/string/index.S @@ -46,14 +46,14 @@ __FBSDID("$FreeBSD$"); LEAF(index) 1: - lbu a2, 0(a0) # get a byte - addu a0, a0, 1 - beq a2, a1, fnd - bne a2, zero, 1b + lbu a2, 0(a0) # get a byte + PTR_ADDU a0, a0, 1 + beq a2, a1, fnd + bne a2, zero, 1b notfnd: - move v0, zero - j ra + move v0, zero + j ra fnd: - subu v0, a0, 1 - j ra + PTR_SUBU v0, a0, 1 + j ra END(index) diff --git a/lib/libc/mips/string/rindex.S b/lib/libc/mips/string/rindex.S index 60cbb48..e50379e 100644 --- a/lib/libc/mips/string/rindex.S +++ b/lib/libc/mips/string/rindex.S @@ -45,13 +45,13 @@ __FBSDID("$FreeBSD$"); #endif LEAF(rindex) - move v0, zero # default if not found + move v0, zero # default if not found 1: - lbu a3, 0(a0) # get a byte - addu a0, a0, 1 - bne a3, a1, 2f - subu v0, a0, 1 # save address of last match + 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 + bne a3, zero, 1b # continue if not end + j ra END(rindex) diff --git a/lib/libc/mips/string/strcmp.S b/lib/libc/mips/string/strcmp.S index ce2839d..8a99056 100644 --- a/lib/libc/mips/string/strcmp.S +++ b/lib/libc/mips/string/strcmp.S @@ -1,4 +1,4 @@ -/* $NetBSD: strcmp.S,v 1.1 2005/12/20 19:28:50 christos Exp $ */ +/* $NetBSD: strcmp.S,v 1.2 2009/12/14 00:39:00 matt Exp $ */ /*- * Copyright (c) 1991, 1993 @@ -37,7 +37,7 @@ __FBSDID("$FreeBSD$"); #if defined(LIBC_SCCS) && !defined(lint) ASMSTR("from: @(#)strcmp.s 8.1 (Berkeley) 6/4/93") - ASMSTR("$NetBSD: strcmp.S,v 1.1 2005/12/20 19:28:50 christos Exp $") + ASMSTR("$NetBSD: strcmp.S,v 1.2 2009/12/14 00:39:00 matt Exp $") #endif /* LIBC_SCCS and not lint */ #ifdef __ABICALLS__ @@ -55,9 +55,9 @@ LEAF(strcmp) bne t0, t1, NotEq lbu t0, 1(a0) # unroll loop lbu t1, 1(a1) - add a0, a0, 2 + PTR_ADD a0, a0, 2 beq t0, zero, LessOrEq # end of first string? - add a1, a1, 2 + PTR_ADD a1, a1, 2 beq t0, t1, 1b NotEq: subu v0, t0, t1 diff --git a/lib/libc/mips/string/strlen.S b/lib/libc/mips/string/strlen.S index c1f302d..3b46ccc 100644 --- a/lib/libc/mips/string/strlen.S +++ b/lib/libc/mips/string/strlen.S @@ -1,4 +1,4 @@ -/* $NetBSD: strlen.S,v 1.1 2005/12/20 19:28:50 christos Exp $ */ +/* $NetBSD: strlen.S,v 1.2 2009/12/14 00:39:00 matt Exp $ */ /*- * Copyright (c) 1991, 1993 @@ -37,7 +37,7 @@ __FBSDID("$FreeBSD$"); #if defined(LIBC_SCCS) && !defined(lint) ASMSTR("from: @(#)strlen.s 8.1 (Berkeley) 6/4/93") - ASMSTR("$NetBSD: strlen.S,v 1.1 2005/12/20 19:28:50 christos Exp $") + ASMSTR("$NetBSD: strlen.S,v 1.2 2009/12/14 00:39:00 matt Exp $") #endif /* LIBC_SCCS and not lint */ #ifdef __ABICALLS__ @@ -45,11 +45,11 @@ __FBSDID("$FreeBSD$"); #endif LEAF(strlen) - addu v1, a0, 1 + PTR_ADDU v1, a0, 1 1: - lb v0, 0(a0) # get byte from string - addu a0, a0, 1 # increment pointer - bne v0, zero, 1b # continue if not end - subu v0, a0, v1 # compute length - 1 for '\0' char - j ra + 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/lib/libc/mips/sys/Makefile.inc b/lib/libc/mips/sys/Makefile.inc index d2e7291..3601909 100644 --- a/lib/libc/mips/sys/Makefile.inc +++ b/lib/libc/mips/sys/Makefile.inc @@ -1,7 +1,7 @@ # $FreeBSD$ MDASM= Ovfork.S brk.S cerror.S exect.S \ - fork.S pipe.S ptrace.S sbrk.S shmat.S syscall.S + fork.S pipe.S ptrace.S sbrk.S syscall.S # Don't generate default code for these syscalls: NOASM= break.o exit.o ftruncate.o getlogin.o lseek.o mmap.o \ diff --git a/lib/libc/mips/sys/Ovfork.S b/lib/libc/mips/sys/Ovfork.S index 99a5526..9df93ea 100644 --- a/lib/libc/mips/sys/Ovfork.S +++ b/lib/libc/mips/sys/Ovfork.S @@ -49,21 +49,16 @@ __FBSDID("$FreeBSD$"); */ LEAF(__sys_vfork) -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - .set reorder -#endif WEAK_ALIAS(vfork, __sys_vfork) WEAK_ALIAS(_vfork, __sys_vfork) + PIC_PROLOGUE(__sys_vfork) li v0, SYS_vfork # system call number for vfork syscall beq a3, zero, 1f # jump if no errors - la t9, __cerror - jr t9 + PIC_TAILCALL(__cerror) 1: beq v1, zero, 2f # parent process ? move v0, zero # return zero in child 2: - j ra + PIC_RETURN() END(__sys_vfork) diff --git a/lib/libc/mips/sys/brk.S b/lib/libc/mips/sys/brk.S index aeaf791..68f0bd4 100644 --- a/lib/libc/mips/sys/brk.S +++ b/lib/libc/mips/sys/brk.S @@ -47,27 +47,25 @@ __FBSDID("$FreeBSD$"); .data _C_LABEL(minbrk): - .word _C_LABEL(_end) + PTR_WORD _C_LABEL(_end) + .text LEAF(__sys_brk) WEAK_ALIAS(brk, __sys_brk) WEAK_ALIAS(_brk, __sys_brk) -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - .set reorder -#endif - lw v0, _C_LABEL(minbrk) + PIC_PROLOGUE(__sys_brk) + PTR_LA v0, _C_LABEL(minbrk) + PTR_L v0, 0(v0) bgeu a0, v0, 1f move a0, v0 # dont allow break < minbrk 1: li v0, SYS_break syscall bne a3, zero, 2f - sw a0, _C_LABEL(__curbrk) + PTR_LA t0, _C_LABEL(__curbrk) + PTR_S a0, 0(t0) move v0, zero - j ra + PIC_RETURN() 2: - la t9, _C_LABEL(__cerror) - jr t9 + PIC_TAILCALL(__cerror) END(__sys_brk) diff --git a/lib/libc/mips/sys/cerror.S b/lib/libc/mips/sys/cerror.S index 535fbe0..c504d73 100644 --- a/lib/libc/mips/sys/cerror.S +++ b/lib/libc/mips/sys/cerror.S @@ -1,4 +1,4 @@ -/* $NetBSD: cerror.S,v 1.13 2003/08/07 16:42:17 agc Exp $ */ +/* $NetBSD: cerror.S,v 1.14 2009/12/14 01:07:42 matt Exp $ */ /*- * Copyright (c) 1991, 1993 @@ -37,35 +37,36 @@ __FBSDID("$FreeBSD$"); #include "SYS.h" #if defined(LIBC_SCCS) && !defined(lint) - ASMSTR("from: @(#)cerror.s 8.1 (Berkeley) 6/16/93") - ASMSTR("$NetBSD: cerror.S,v 1.13 2003/08/07 16:42:17 agc Exp $") +#if 0 + RCSID("from: @(#)cerror.s 8.1 (Berkeley) 6/16/93") +#else + RCSID("$NetBSD: cerror.S,v 1.14 2009/12/14 01:07:42 matt Exp $") +#endif #endif /* LIBC_SCCS and not lint */ + .globl _C_LABEL(__error) +NESTED_NOPROFILE(__cerror, CALLFRAME_SIZ, ra) + .mask 0x80000000, (CALLFRAME_RA - CALLFRAME_SIZ) + SETUP_GP + PTR_SUBU sp, sp, CALLFRAME_SIZ + SETUP_GP64(CALLFRAME_GP, __cerror) + SAVE_GP(CALLFRAME_GP) - /* - * The __error() function is thread aware. For non-threaded - * programs and the initial threaded in threaded programs, - * it returns a pointer to the global errno variable. - */ - .globl _C_LABEL(__error) - .type _C_LABEL(__error),%function + PTR_S ra, CALLFRAME_RA(sp) + REG_S v0, CALLFRAME_S0(sp) # save errno value -LEAF(__cerror) - .frame sp, CALLFRAME_SIZ, ra - PIC_PROLOGUE(__cerror, t9) - subu sp, sp, CALLFRAME_SIZ - .mask 0x80000000, (CALLFRAME_RA - CALLFRAME_SIZ) - sw ra, CALLFRAME_RA(sp) - sw v0, 12(sp) # save errno value + PTR_LA t9, _C_LABEL(__error) # locate address of errno + jalr t9 + + REG_L t0, CALLFRAME_S0(sp) + PTR_L ra, CALLFRAME_RA(sp) + INT_S t0, 0(v0) # update errno value + + RESTORE_GP64 + PTR_ADDU sp, sp, CALLFRAME_SIZ - la t9, _C_LABEL(__error) # locate address of errno - jalr t9 + li v0, -1 + li v1, -1 - lw t0, 12(sp) - lw ra, CALLFRAME_RA(sp) - sw t0, 0(v0) # update errno value - addiu sp, sp, CALLFRAME_SIZ - li v0, -1 - li v1, -1 - j ra + j ra END(__cerror) diff --git a/lib/libc/mips/sys/exect.S b/lib/libc/mips/sys/exect.S index 702015d..613d47c 100644 --- a/lib/libc/mips/sys/exect.S +++ b/lib/libc/mips/sys/exect.S @@ -41,16 +41,11 @@ __FBSDID("$FreeBSD$"); #endif /* LIBC_SCCS and not lint */ LEAF(exect) -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - .set reorder -#endif + PIC_PROLOGUE(exect) li v0, SYS_execve syscall bne a3, zero, 1f - j ra + PIC_RETURN() 1: - la t9, _C_LABEL(__cerror) - jr t9 + PIC_TAILCALL(__cerror) END(exect) diff --git a/lib/libc/mips/sys/fork.S b/lib/libc/mips/sys/fork.S index 2d1f14b..7636bd3 100644 --- a/lib/libc/mips/sys/fork.S +++ b/lib/libc/mips/sys/fork.S @@ -44,20 +44,14 @@ __FBSDID("$FreeBSD$"); LEAF(__sys_fork) WEAK_ALIAS(fork, __sys_fork) WEAK_ALIAS(_fork, __sys_fork) -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - .set reorder -#endif - fork = __sys_fork + PIC_PROLOGUE(__sys_fork) li v0, SYS_fork # pid = fork() syscall bne a3, zero, 2f beq v1, zero, 1f # v1 == 0 in parent, 1 in child move v0, zero 1: - j ra + PIC_RETURN() 2: - la t9, _C_LABEL(__cerror) - jr t9 + PIC_TAILCALL(__cerror) END(__sys_fork) diff --git a/lib/libc/mips/sys/pipe.S b/lib/libc/mips/sys/pipe.S index 224b78c..0146532 100644 --- a/lib/libc/mips/sys/pipe.S +++ b/lib/libc/mips/sys/pipe.S @@ -44,19 +44,14 @@ __FBSDID("$FreeBSD$"); LEAF(__sys_pipe) WEAK_ALIAS(pipe, __sys_pipe) WEAK_ALIAS(_pipe, __sys_pipe) -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - .set reorder -#endif + PIC_PROLOGUE(__sys_pipe) li v0, SYS_pipe # pipe(fildes) int fildes[2]; syscall bne a3, zero, 1f sw v0, 0(a0) # store the two file descriptors sw v1, 4(a0) move v0, zero - j ra + PIC_RETURN() 1: - la t9, _C_LABEL(__cerror) - jr t9 + PIC_TAILCALL(__cerror) END(__sys_pipe) diff --git a/lib/libc/mips/sys/ptrace.S b/lib/libc/mips/sys/ptrace.S index 09b82c5..8cf984a9 100644 --- a/lib/libc/mips/sys/ptrace.S +++ b/lib/libc/mips/sys/ptrace.S @@ -41,32 +41,31 @@ __FBSDID("$FreeBSD$"); ASMSTR("$NetBSD: ptrace.S,v 1.9 2003/08/07 16:42:17 agc Exp $") #endif /* LIBC_SCCS and not lint */ -LEAF(ptrace) - .frame sp, 40, ra - .mask 0x80000000, -8 -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - .set reorder -#endif - subu sp, sp, 40 - sw ra, 32(sp) -#ifdef __ABICALLS__ - .cprestore 16 -#endif - la t9, _C_LABEL(__error) # locate address of errno - jalr t9 -#ifdef __ABICALLS__ - lw gp, 16(sp) -#endif - sw zero, 0(v0) - lw ra, 32(sp) - addu sp, sp, 40 - li v0, SYS_ptrace +NESTED_NOPROFILE(ptrace, CALLFRAME_SIZ, ra) + .mask 0x80000000, (CALLFRAME_RA - CALLFRAME_SIZ) + SETUP_GP + PTR_SUBU sp, sp, CALLFRAME_SIZ + SETUP_GP64(CALLFRAME_GP, ptrace) + SAVE_GP(CALLFRAME_GP) + + PTR_S ra, CALLFRAME_RA(sp) + + PTR_LA t9, _C_LABEL(__error) # locate address of errno + jalr t9 + + PTR_L ra, CALLFRAME_RA(sp) + INT_S zero, 0(v0) # update errno value + + li v0, SYS_ptrace syscall - bne a3, zero, 1f - j ra -1: - la t9, _C_LABEL(__cerror) - jr t9 + + # Load __cerror's address using our gp, then restore it. + PTR_LA t9, __cerror + RESTORE_GP64 + PTR_ADDU sp, sp, CALLFRAME_SIZ + + bne a3, zero, 1f + + j ra +1: j t9 END(ptrace) diff --git a/lib/libc/mips/sys/sbrk.S b/lib/libc/mips/sys/sbrk.S index c535360..0989493 100644 --- a/lib/libc/mips/sys/sbrk.S +++ b/lib/libc/mips/sys/sbrk.S @@ -46,40 +46,28 @@ __FBSDID("$FreeBSD$"); .data _C_LABEL(__curbrk): - .word _C_LABEL(_end) + PTR_WORD _C_LABEL(_end) .text LEAF(__sys_sbrk) WEAK_ALIAS(sbrk, __sys_sbrk) WEAK_ALIAS(_sbrk, __sys_sbrk) -#ifdef __ABICALLS__ - .set noreorder - .cpload t9 - .set reorder -#endif - addu sp, sp, -16 - sw s0, 0(sp) # Preserve s0 value in stack - # it should be the same on return - # We can't use v1 as temporary - # register since syscall uses it - # to return 64-bit values - lw s0, _C_LABEL(__curbrk) - li v0, SYS_break - addu a0, a0, s0 # compute current break + PIC_PROLOGUE(__sys_sbrk) + PTR_LA t0, _C_LABEL(__curbrk) + PTR_L t0, 0(t0) + PTR_ADDU a0, a0, t0 + li v0, SYS_break syscall bne a3, zero, 1f nop - move v0, s0 # return old val of curbrk from above - lw s0, 0(sp) - addu sp, sp, 16 - sw a0, _C_LABEL(__curbrk) # save current val of curbrk from above + move v0, t0 # 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() j ra 1: - lw s0, 0(sp) - addu sp, sp, 16 - la t9, _C_LABEL(__cerror) - jr t9 + PIC_TAILCALL(__cerror) END(__sys_sbrk) diff --git a/lib/libc/net/ethers.3 b/lib/libc/net/ethers.3 index 3148b6c..c8aa51a 100644 --- a/lib/libc/net/ethers.3 +++ b/lib/libc/net/ethers.3 @@ -189,7 +189,7 @@ unable to find a match in the .Pa /etc/ethers database. .Sh NOTES -The user must insure that the hostname strings passed to the +The user must ensure that the hostname strings passed to the .Fn ether_line , .Fn ether_ntohost and diff --git a/lib/libc/net/eui64.3 b/lib/libc/net/eui64.3 index 3000c74..7cc5718 100644 --- a/lib/libc/net/eui64.3 +++ b/lib/libc/net/eui64.3 @@ -189,7 +189,7 @@ unable to find a match in the .Pa /etc/eui64 database. .Sh NOTES -The user must insure that the hostname strings passed to the +The user must ensure that the hostname strings passed to the .\" .Fn eui64_line , .Fn eui64_ntohost and diff --git a/lib/libc/net/gethostbydns.c b/lib/libc/net/gethostbydns.c index ff93972..f301c88 100644 --- a/lib/libc/net/gethostbydns.c +++ b/lib/libc/net/gethostbydns.c @@ -522,23 +522,34 @@ _dns_gethostbyname(void *rval, void *cb_data, va_list ap) free(buf); dprintf("res_nsearch failed (%d)\n", n, statp); *h_errnop = statp->res_h_errno; - return (0); + return (NS_NOTFOUND); } else if (n > sizeof(buf->buf)) { free(buf); dprintf("static buffer is too small (%d)\n", n, statp); *h_errnop = statp->res_h_errno; - return (0); + return (NS_UNAVAIL); } error = gethostanswer(buf, n, name, type, &he, hed, statp); free(buf); if (error != 0) { *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + switch (statp->res_h_errno) { + case HOST_NOT_FOUND: + return (NS_NOTFOUND); + case TRY_AGAIN: + return (NS_TRYAGAIN); + default: + return (NS_UNAVAIL); + } + /*NOTREACHED*/ } if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } + RES_SET_H_ERRNO(statp, NETDB_SUCCESS); *((struct hostent **)rval) = hptr; return (NS_SUCCESS); } @@ -629,7 +640,15 @@ _dns_gethostbyaddr(void *rval, void *cb_data, va_list ap) if (gethostanswer(buf, n, qbuf, T_PTR, &he, hed, statp) != 0) { free(buf); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); /* h_errno was set by gethostanswer() */ + switch (statp->res_h_errno) { + case HOST_NOT_FOUND: + return (NS_NOTFOUND); + case TRY_AGAIN: + return (NS_TRYAGAIN); + default: + return (NS_UNAVAIL); + } + /*NOTREACHED*/ } free(buf); #ifdef SUNSECURITY @@ -683,11 +702,13 @@ _dns_gethostbyaddr(void *rval, void *cb_data, va_list ap) he.h_addrtype = AF_INET6; he.h_length = NS_IN6ADDRSZ; } - RES_SET_H_ERRNO(statp, NETDB_SUCCESS); if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } + RES_SET_H_ERRNO(statp, NETDB_SUCCESS); *((struct hostent **)rval) = hptr; return (NS_SUCCESS); } diff --git a/lib/libc/net/gethostbyht.c b/lib/libc/net/gethostbyht.c index 8c41d9a..4253d49 100644 --- a/lib/libc/net/gethostbyht.c +++ b/lib/libc/net/gethostbyht.c @@ -60,6 +60,7 @@ __FBSDID("$FreeBSD$"); #include <netdb.h> #include <stdio.h> #include <ctype.h> +#include <errno.h> #include <string.h> #include <stdarg.h> #include <nsswitch.h> @@ -192,8 +193,11 @@ gethostent_r(struct hostent *hptr, char *buffer, size_t buflen, } if (gethostent_p(&he, hed, statp->options & RES_USE_INET6, statp) != 0) return (-1); - if (__copy_hostent(&he, hptr, buffer, buflen) != 0) - return (-1); + if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return ((errno != 0) ? errno : -1); + } *result = hptr; return (0); } @@ -268,8 +272,10 @@ found: return (NS_NOTFOUND); } if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct hostent **)rval) = hptr; return (NS_SUCCESS); @@ -323,8 +329,10 @@ _ht_gethostbyaddr(void *rval, void *cb_data, va_list ap) if (error != 0) return (NS_NOTFOUND); if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct hostent **)rval) = hptr; return (NS_SUCCESS); diff --git a/lib/libc/net/gethostbynis.c b/lib/libc/net/gethostbynis.c index 7921ced..11de8ae 100644 --- a/lib/libc/net/gethostbynis.c +++ b/lib/libc/net/gethostbynis.c @@ -288,8 +288,10 @@ _nis_gethostbyname(void *rval, void *cb_data, va_list ap) return (NS_NOTFOUND); } if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct hostent **)rval) = hptr; return (NS_SUCCESS); @@ -336,8 +338,10 @@ _nis_gethostbyaddr(void *rval, void *cb_data, va_list ap) return (NS_NOTFOUND); } if (__copy_hostent(&he, hptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct hostent **)rval) = hptr; return (NS_SUCCESS); diff --git a/lib/libc/net/gethostnamadr.c b/lib/libc/net/gethostnamadr.c index ffad6f2..2dc9d02 100644 --- a/lib/libc/net/gethostnamadr.c +++ b/lib/libc/net/gethostnamadr.c @@ -480,8 +480,12 @@ fakeaddr(const char *name, int af, struct hostent *hp, char *buf, hed->h_addr_ptrs[0] = (char *)hed->host_addr; hed->h_addr_ptrs[1] = NULL; he.h_addr_list = hed->h_addr_ptrs; + if (__copy_hostent(&he, hp, buf, buflen) != 0) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + return (-1); + } RES_SET_H_ERRNO(statp, NETDB_SUCCESS); - return (__copy_hostent(&he, hp, buf, buflen)); + return (0); } int @@ -528,7 +532,7 @@ gethostbyname_internal(const char *name, int af, struct hostent *hp, char *buf, size_t buflen, struct hostent **result, int *h_errnop, res_state statp) { const char *cp; - int rval, ret_errno; + int rval, ret_errno = 0; char abuf[MAXDNAME]; #ifdef NS_CACHING @@ -576,7 +580,11 @@ gethostbyname_internal(const char *name, int af, struct hostent *hp, char *buf, "gethostbyname2_r", default_src, name, af, hp, buf, buflen, &ret_errno, h_errnop); - return ((rval == NS_SUCCESS) ? 0 : -1); + if (rval != NS_SUCCESS) { + errno = ret_errno; + return ((ret_errno != 0) ? ret_errno : -1); + } + return (0); } int @@ -586,7 +594,7 @@ gethostbyaddr_r(const void *addr, socklen_t len, int af, struct hostent *hp, const u_char *uaddr = (const u_char *)addr; const struct in6_addr *addr6; socklen_t size; - int rval, ret_errno; + int rval, ret_errno = 0; res_state statp; #ifdef NS_CACHING @@ -651,7 +659,11 @@ gethostbyaddr_r(const void *addr, socklen_t len, int af, struct hostent *hp, "gethostbyaddr_r", default_src, uaddr, len, af, hp, buf, buflen, &ret_errno, h_errnop); - return ((rval == NS_SUCCESS) ? 0 : -1); + if (rval != NS_SUCCESS) { + errno = ret_errno; + return ((ret_errno != 0) ? ret_errno : -1); + } + return (0); } struct hostent * diff --git a/lib/libc/net/getnetbydns.c b/lib/libc/net/getnetbydns.c index 6fd7d2f..79e40a5 100644 --- a/lib/libc/net/getnetbydns.c +++ b/lib/libc/net/getnetbydns.c @@ -355,8 +355,10 @@ _dns_getnetbyaddr(void *rval, void *cb_data, va_list ap) net >>= 8; ne.n_net = net; if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct netent **)rval) = nptr; return (NS_SUCCESS); @@ -431,8 +433,10 @@ _dns_getnetbyname(void *rval, void *cb_data, va_list ap) return (NS_NOTFOUND); } if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct netent **)rval) = nptr; return (NS_SUCCESS); diff --git a/lib/libc/net/getnetbyht.c b/lib/libc/net/getnetbyht.c index 2bbba06..d2df570 100644 --- a/lib/libc/net/getnetbyht.c +++ b/lib/libc/net/getnetbyht.c @@ -49,6 +49,7 @@ __FBSDID("$FreeBSD$"); #include <netinet/in.h> #include <arpa/inet.h> #include <arpa/nameser.h> +#include <errno.h> #include <netdb.h> #include <resolv.h> #include <stdio.h> @@ -162,8 +163,11 @@ getnetent_r(struct netent *nptr, char *buffer, size_t buflen, } if (getnetent_p(&ne, ned) != 0) return (-1); - if (__copy_netent(&ne, nptr, buffer, buflen) != 0) - return (-1); + if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); + *h_errnop = statp->res_h_errno; + return ((errno != 0) ? errno : -1); + } *result = nptr; return (0); } @@ -226,8 +230,10 @@ found: return (NS_NOTFOUND); } if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct netent **)rval) = nptr; return (NS_SUCCESS); @@ -272,8 +278,10 @@ _ht_getnetbyaddr(void *rval, void *cb_data, va_list ap) return (NS_NOTFOUND); } if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct netent **)rval) = nptr; return (NS_SUCCESS); diff --git a/lib/libc/net/getnetbynis.c b/lib/libc/net/getnetbynis.c index d00c7f2..811e431 100644 --- a/lib/libc/net/getnetbynis.c +++ b/lib/libc/net/getnetbynis.c @@ -160,8 +160,10 @@ _nis_getnetbyname(void *rval, void *cb_data, va_list ap) return (NS_NOTFOUND); } if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct netent **)rval) = nptr; return (NS_SUCCESS); @@ -244,8 +246,10 @@ _nis_getnetbyaddr(void *rval, void *cb_data, va_list ap) return (NS_NOTFOUND); } if (__copy_netent(&ne, nptr, buffer, buflen) != 0) { + *errnop = errno; + RES_SET_H_ERRNO(statp, NETDB_INTERNAL); *h_errnop = statp->res_h_errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct netent **)rval) = nptr; return (NS_SUCCESS); diff --git a/lib/libc/net/getnetent.3 b/lib/libc/net/getnetent.3 index f408f76..2e9cd33 100644 --- a/lib/libc/net/getnetent.3 +++ b/lib/libc/net/getnetent.3 @@ -72,7 +72,6 @@ system. The order of the lookups is controlled by the `networks' entry in .Xr nsswitch.conf 5 . -.Pp .Bd -literal -offset indent struct netent { char *n_name; /* official name of net */ diff --git a/lib/libc/net/getnetnamadr.c b/lib/libc/net/getnetnamadr.c index ec7e94b..9aa4d51 100644 --- a/lib/libc/net/getnetnamadr.c +++ b/lib/libc/net/getnetnamadr.c @@ -360,13 +360,17 @@ getnetbyname_r(const char *name, struct netent *ne, char *buffer, #endif { 0 } }; - int rval, ret_errno; + int rval, ret_errno = 0; rval = _nsdispatch((void *)result, dtab, NSDB_NETWORKS, "getnetbyname_r", default_src, name, ne, buffer, buflen, &ret_errno, h_errorp); - return ((rval == NS_SUCCESS) ? 0 : -1); + if (rval != NS_SUCCESS) { + errno = ret_errno; + return ((ret_errno != 0) ? ret_errno : -1); + } + return (0); } int @@ -388,13 +392,17 @@ getnetbyaddr_r(uint32_t addr, int af, struct netent *ne, char *buffer, #endif { 0 } }; - int rval, ret_errno; + int rval, ret_errno = 0; rval = _nsdispatch((void *)result, dtab, NSDB_NETWORKS, "getnetbyaddr_r", default_src, addr, af, ne, buffer, buflen, &ret_errno, h_errorp); - return ((rval == NS_SUCCESS) ? 0 : -1); + if (rval != NS_SUCCESS) { + errno = ret_errno; + return ((ret_errno != 0) ? ret_errno : -1); + } + return (0); } struct netent * diff --git a/lib/libc/net/getproto.c b/lib/libc/net/getproto.c index 85b40e1..b923edf 100644 --- a/lib/libc/net/getproto.c +++ b/lib/libc/net/getproto.c @@ -33,6 +33,7 @@ static char sccsid[] = "@(#)getproto.c 8.1 (Berkeley) 6/4/93"; #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); +#include <errno.h> #include <netdb.h> #include <nsswitch.h> #include "netdb_private.h" @@ -72,7 +73,7 @@ files_getprotobynumber(void *retval, void *mdata, va_list ap) errnop = va_arg(ap, int *); if ((ped = __protoent_data_init()) == NULL) { - *errnop = -1; + *errnop = errno; return (NS_NOTFOUND); } @@ -83,12 +84,12 @@ files_getprotobynumber(void *retval, void *mdata, va_list ap) if (!ped->stayopen) __endprotoent_p(ped); if (error != 0) { - *errnop = -1; + *errnop = errno; return (NS_NOTFOUND); } if (__copy_protoent(&pe, pptr, buffer, buflen) != 0) { - *errnop = -1; - return (NS_NOTFOUND); + *errnop = errno; + return (NS_RETURN); } *((struct protoent **)retval) = pptr; @@ -120,10 +121,11 @@ getprotobynumber_r(int proto, struct protoent *pptr, char *buffer, rv = nsdispatch(result, dtab, NSDB_PROTOCOLS, "getprotobynumber_r", defaultsrc, proto, pptr, buffer, buflen, &ret_errno); - if (rv == NS_SUCCESS) - return (0); - else + if (rv != NS_SUCCESS) { + errno = ret_errno; return (ret_errno); + } + return (0); } struct protoent * diff --git a/lib/libc/net/getprotoent.3 b/lib/libc/net/getprotoent.3 index b3ded5d..9f9e00d 100644 --- a/lib/libc/net/getprotoent.3 +++ b/lib/libc/net/getprotoent.3 @@ -64,7 +64,6 @@ following structure containing the broken-out fields of a line in the network protocol data base, .Pa /etc/protocols . -.Pp .Bd -literal -offset indent struct protoent { char *p_name; /* official name of protocol */ diff --git a/lib/libc/net/getprotoent.c b/lib/libc/net/getprotoent.c index dda5d18..0cfca45 100644 --- a/lib/libc/net/getprotoent.c +++ b/lib/libc/net/getprotoent.c @@ -424,8 +424,10 @@ files_getprotoent_r(void *retval, void *mdata, va_list ap) buflen = va_arg(ap, size_t); errnop = va_arg(ap, int *); - if ((ped = __protoent_data_init()) == NULL) - return (-1); + if ((ped = __protoent_data_init()) == NULL) { + *errnop = errno; + return (NS_NOTFOUND); + } if (__getprotoent_p(&pe, ped) != 0) { *errnop = errno; @@ -434,7 +436,7 @@ files_getprotoent_r(void *retval, void *mdata, va_list ap) if (__copy_protoent(&pe, pptr, buffer, buflen) != 0) { *errnop = errno; - return (NS_NOTFOUND); + return (NS_RETURN); } *((struct protoent **)retval) = pptr; @@ -490,10 +492,11 @@ getprotoent_r(struct protoent *pptr, char *buffer, size_t buflen, rv = nsdispatch(result, dtab, NSDB_PROTOCOLS, "getprotoent_r", defaultsrc, pptr, buffer, buflen, &ret_errno); - if (rv == NS_SUCCESS) - return (0); - else + if (rv != NS_SUCCESS) { + errno = ret_errno; return (ret_errno); + } + return (0); } void diff --git a/lib/libc/net/getprotoname.c b/lib/libc/net/getprotoname.c index bead63a..22c5759 100644 --- a/lib/libc/net/getprotoname.c +++ b/lib/libc/net/getprotoname.c @@ -33,6 +33,7 @@ static char sccsid[] = "@(#)getprotoname.c 8.1 (Berkeley) 6/4/93"; #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); +#include <errno.h> #include <netdb.h> #include <nsswitch.h> #include <string.h> @@ -75,7 +76,7 @@ files_getprotobyname(void *retval, void *mdata, va_list ap) if ((ped = __protoent_data_init()) == NULL) { - *errnop = -1; + *errnop = errno; return (NS_NOTFOUND); } @@ -91,12 +92,12 @@ found: if (!ped->stayopen) __endprotoent_p(ped); if (error != 0) { - *errnop = -1; + *errnop = errno; return (NS_NOTFOUND); } if (__copy_protoent(&pe, pptr, buffer, buflen) != 0) { - *errnop = -1; - return (NS_NOTFOUND); + *errnop = errno; + return (NS_RETURN); } *((struct protoent **)retval) = pptr; @@ -128,10 +129,11 @@ getprotobyname_r(const char *name, struct protoent *pptr, char *buffer, rv = nsdispatch(result, dtab, NSDB_PROTOCOLS, "getprotobyname_r", defaultsrc, name, pptr, buffer, buflen, &ret_errno); - if (rv == NS_SUCCESS) - return (0); - else + if (rv != NS_SUCCESS) { + errno = ret_errno; return (ret_errno); + } + return (0); } struct protoent * diff --git a/lib/libc/net/getservent.c b/lib/libc/net/getservent.c index ebb7a7d..3228bdc 100644 --- a/lib/libc/net/getservent.c +++ b/lib/libc/net/getservent.c @@ -37,7 +37,9 @@ __FBSDID("$FreeBSD$"); #include <sys/types.h> #include <sys/socket.h> #include <arpa/inet.h> +#include <db.h> #include <errno.h> +#include <fcntl.h> #include <limits.h> #include <netdb.h> #include <nsswitch.h> @@ -94,6 +96,19 @@ NSS_TLS_HANDLING(files); static int files_servent(void *, void *, va_list); static int files_setservent(void *, void *, va_list); +/* db backend declarations */ +struct db_state +{ + DB *db; + int stayopen; + int keynum; +}; +static void db_endstate(void *); +NSS_TLS_HANDLING(db); + +static int db_servent(void *, void *, va_list); +static int db_setservent(void *, void *, va_list); + #ifdef YP /* nis backend declarations */ static int nis_servent(void *, void *, va_list); @@ -207,6 +222,32 @@ servent_unpack(char *p, struct servent *serv, char **aliases, return 0; } +static int +parse_result(struct servent *serv, char *buffer, size_t bufsize, + char *resultbuf, size_t resultbuflen, int *errnop) +{ + char **aliases; + int aliases_size; + + if (bufsize <= resultbuflen + _ALIGNBYTES + sizeof(char *)) { + *errnop = ERANGE; + return (NS_RETURN); + } + aliases = (char **)_ALIGN(&buffer[resultbuflen + 1]); + aliases_size = (buffer + bufsize - (char *)aliases) / sizeof(char *); + if (aliases_size < 1) { + *errnop = ERANGE; + return (NS_RETURN); + } + + memcpy(buffer, resultbuf, resultbuflen); + buffer[resultbuflen] = '\0'; + + if (servent_unpack(buffer, serv, aliases, aliases_size, errnop) != 0) + return ((*errnop == 0) ? NS_NOTFOUND : NS_RETURN); + return (NS_SUCCESS); +} + /* files backend implementation */ static void files_endstate(void *p) @@ -237,6 +278,8 @@ files_servent(void *retval, void *mdata, va_list ap) { NULL, 0 } }; ns_dtab compat_dtab[] = { + { NSSRC_DB, db_servent, + (void *)((struct servent_mdata *)mdata)->how }, #ifdef YP { NSSRC_NIS, nis_servent, (void *)((struct servent_mdata *)mdata)->how }, @@ -258,8 +301,6 @@ files_servent(void *retval, void *mdata, va_list ap) size_t bufsize; int *errnop; - char **aliases; - int aliases_size; size_t linesize; char *line; char **cp; @@ -315,28 +356,8 @@ files_servent(void *retval, void *mdata, va_list ap) break; } - if (*line=='+') { - if (serv_mdata->compat_mode != 0) - st->compat_mode_active = 1; - } else { - if (bufsize <= linesize + _ALIGNBYTES + - sizeof(char *)) { - *errnop = ERANGE; - rv = NS_RETURN; - break; - } - aliases = (char **)_ALIGN(&buffer[linesize+1]); - aliases_size = (buffer + bufsize - - (char *)aliases) / sizeof(char *); - if (aliases_size < 1) { - *errnop = ERANGE; - rv = NS_RETURN; - break; - } - - memcpy(buffer, line, linesize); - buffer[linesize] = '\0'; - } + if (*line=='+' && serv_mdata->compat_mode != 0) + st->compat_mode_active = 1; } if (st->compat_mode_active != 0) { @@ -367,18 +388,12 @@ files_servent(void *retval, void *mdata, va_list ap) continue; } - rv = servent_unpack(buffer, serv, aliases, aliases_size, + rv = parse_result(serv, buffer, bufsize, line, linesize, errnop); - if (rv !=0 ) { - if (*errnop == 0) { - rv = NS_NOTFOUND; - continue; - } - else { - rv = NS_RETURN; - break; - } - } + if (rv == NS_NOTFOUND) + continue; + if (rv == NS_RETURN) + break; rv = NS_NOTFOUND; switch (serv_mdata->how) { @@ -454,6 +469,183 @@ files_setservent(void *retval, void *mdata, va_list ap) return (NS_UNAVAIL); } +/* db backend implementation */ +static void +db_endstate(void *p) +{ + DB *db; + + if (p == NULL) + return; + + db = ((struct db_state *)p)->db; + if (db != NULL) + db->close(db); + + free(p); +} + +static int +db_servent(void *retval, void *mdata, va_list ap) +{ + char buf[BUFSIZ]; + DBT key, data, *result; + DB *db; + + struct db_state *st; + int rv; + int stayopen; + + enum nss_lookup_type how; + char *name; + char *proto; + int port; + + struct servent *serv; + char *buffer; + size_t bufsize; + int *errnop; + + name = NULL; + proto = NULL; + how = (enum nss_lookup_type)mdata; + switch (how) { + case nss_lt_name: + name = va_arg(ap, char *); + proto = va_arg(ap, char *); + break; + case nss_lt_id: + port = va_arg(ap, int); + proto = va_arg(ap, char *); + break; + case nss_lt_all: + break; + default: + return NS_NOTFOUND; + }; + + serv = va_arg(ap, struct servent *); + buffer = va_arg(ap, char *); + bufsize = va_arg(ap, size_t); + errnop = va_arg(ap,int *); + + *errnop = db_getstate(&st); + if (*errnop != 0) + return (NS_UNAVAIL); + + if (how == nss_lt_all && st->keynum < 0) + return (NS_NOTFOUND); + + if (st->db == NULL) { + st->db = dbopen(_PATH_SERVICES_DB, O_RDONLY, 0, DB_HASH, NULL); + if (st->db == NULL) { + *errnop = errno; + return (NS_UNAVAIL); + } + } + + stayopen = (how == nss_lt_all) ? 1 : st->stayopen; + db = st->db; + + do { + switch (how) { + case nss_lt_name: + key.data = buf; + if (proto == NULL) + key.size = snprintf(buf, sizeof(buf), + "\376%s", name); + else + key.size = snprintf(buf, sizeof(buf), + "\376%s/%s", name, proto); + key.size++; + if (db->get(db, &key, &data, 0) != 0 || + db->get(db, &data, &key, 0) != 0) { + rv = NS_NOTFOUND; + goto db_fin; + } + result = &key; + break; + case nss_lt_id: + key.data = buf; + port = htons(port); + if (proto == NULL) + key.size = snprintf(buf, sizeof(buf), + "\377%d", port); + else + key.size = snprintf(buf, sizeof(buf), + "\377%d/%s", port, proto); + key.size++; + if (db->get(db, &key, &data, 0) != 0 || + db->get(db, &data, &key, 0) != 0) { + rv = NS_NOTFOUND; + goto db_fin; + } + result = &key; + break; + case nss_lt_all: + key.data = buf; + key.size = snprintf(buf, sizeof(buf), "%d", + st->keynum++); + key.size++; + if (db->get(db, &key, &data, 0) != 0) { + st->keynum = -1; + rv = NS_NOTFOUND; + goto db_fin; + } + result = &data; + break; + } + + rv = parse_result(serv, buffer, bufsize, result->data, + result->size - 1, errnop); + + } while (!(rv & NS_TERMINATE) && how == nss_lt_all); + +db_fin: + if (!stayopen && st->db != NULL) { + db->close(db); + st->db = NULL; + } + + if (rv == NS_SUCCESS && retval != NULL) + *(struct servent **)retval = serv; + + return (rv); +} + +static int +db_setservent(void *retval, void *mdata, va_list ap) +{ + DB *db; + struct db_state *st; + int rv; + int f; + + rv = db_getstate(&st); + if (rv != 0) + return (NS_UNAVAIL); + + switch ((enum constants)mdata) { + case SETSERVENT: + f = va_arg(ap, int); + st->stayopen |= f; + st->keynum = 0; + break; + case ENDSERVENT: + db = st->db; + if (db != NULL) { + db->close(db); + st->db = NULL; + } + st->stayopen = 0; + break; + default: + break; + }; + + return (NS_UNAVAIL); +} + /* nis backend implementation */ #ifdef YP static void @@ -486,9 +678,6 @@ nis_servent(void *retval, void *mdata, va_list ap) size_t bufsize; int *errnop; - char **aliases; - int aliases_size; - name = NULL; proto = NULL; how = (enum nss_lookup_type)mdata; @@ -594,39 +783,8 @@ nis_servent(void *retval, void *mdata, va_list ap) break; }; - /* we need a room for additional \n symbol */ - if (bufsize <= - resultbuflen + 1 + _ALIGNBYTES + sizeof(char *)) { - *errnop = ERANGE; - rv = NS_RETURN; - break; - } - - aliases = (char **)_ALIGN(&buffer[resultbuflen + 2]); - aliases_size = - (buffer + bufsize - (char *)aliases) / sizeof(char *); - if (aliases_size < 1) { - *errnop = ERANGE; - rv = NS_RETURN; - break; - } - - /* - * servent_unpack expects lines terminated with \n -- - * make it happy - */ - memcpy(buffer, resultbuf, resultbuflen); - buffer[resultbuflen] = '\n'; - buffer[resultbuflen + 1] = '\0'; - - if (servent_unpack(buffer, serv, aliases, aliases_size, - errnop) != 0) { - if (*errnop == 0) - rv = NS_NOTFOUND; - else - rv = NS_RETURN; - } else - rv = NS_SUCCESS; + rv = parse_result(serv, buffer, bufsize, resultbuf, + resultbuflen, errnop); free(resultbuf); } while (!(rv & NS_TERMINATE) && how == nss_lt_all); @@ -674,6 +832,7 @@ compat_setservent(void *retval, void *mdata, va_list ap) { NULL, 0 } }; ns_dtab compat_dtab[] = { + { NSSRC_DB, db_setservent, mdata }, #ifdef YP { NSSRC_NIS, nis_setservent, mdata }, #endif @@ -960,6 +1119,7 @@ getservbyname_r(const char *name, const char *proto, struct servent *serv, #endif /* NS_CACHING */ static const ns_dtab dtab[] = { { NSSRC_FILES, files_servent, (void *)&mdata }, + { NSSRC_DB, db_servent, (void *)nss_lt_name }, #ifdef YP { NSSRC_NIS, nis_servent, (void *)nss_lt_name }, #endif @@ -996,6 +1156,7 @@ getservbyport_r(int port, const char *proto, struct servent *serv, #endif static const ns_dtab dtab[] = { { NSSRC_FILES, files_servent, (void *)&mdata }, + { NSSRC_DB, db_servent, (void *)nss_lt_id }, #ifdef YP { NSSRC_NIS, nis_servent, (void *)nss_lt_id }, #endif @@ -1031,6 +1192,7 @@ getservent_r(struct servent *serv, char *buffer, size_t bufsize, #endif static const ns_dtab dtab[] = { { NSSRC_FILES, files_servent, (void *)&mdata }, + { NSSRC_DB, db_servent, (void *)nss_lt_all }, #ifdef YP { NSSRC_NIS, nis_servent, (void *)nss_lt_all }, #endif @@ -1063,6 +1225,7 @@ setservent(int stayopen) #endif static const ns_dtab dtab[] = { { NSSRC_FILES, files_setservent, (void *)SETSERVENT }, + { NSSRC_DB, db_setservent, (void *)SETSERVENT }, #ifdef YP { NSSRC_NIS, nis_setservent, (void *)SETSERVENT }, #endif @@ -1087,6 +1250,7 @@ endservent() #endif static const ns_dtab dtab[] = { { NSSRC_FILES, files_setservent, (void *)ENDSERVENT }, + { NSSRC_DB, db_setservent, (void *)ENDSERVENT }, #ifdef YP { NSSRC_NIS, nis_setservent, (void *)ENDSERVENT }, #endif diff --git a/lib/libc/net/hesiod.c b/lib/libc/net/hesiod.c index c22bdba..2413727 100644 --- a/lib/libc/net/hesiod.c +++ b/lib/libc/net/hesiod.c @@ -324,6 +324,7 @@ read_config_file(ctx, filename) ? &ctx->lhs : &ctx->rhs; *which = strdup(data); if (!*which) { + fclose(fp); errno = ENOMEM; return -1; } diff --git a/lib/libc/net/inet6_rth_space.3 b/lib/libc/net/inet6_rth_space.3 index 2750170..a3db794 100644 --- a/lib/libc/net/inet6_rth_space.3 +++ b/lib/libc/net/inet6_rth_space.3 @@ -101,7 +101,8 @@ 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 +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. diff --git a/lib/libc/net/nsdispatch.3 b/lib/libc/net/nsdispatch.3 index cf15002..d1d8d5a 100644 --- a/lib/libc/net/nsdispatch.3 +++ b/lib/libc/net/nsdispatch.3 @@ -32,7 +32,7 @@ .\" .\" $FreeBSD$ .\" -.Dd January 22, 2007 +.Dd April 4, 2010 .Dt NSDISPATCH 3 .Os .Sh NAME @@ -85,7 +85,6 @@ typedef struct _ns_dtab { void *mdata; } ns_dtab; .Ed -.Pp .Bd -ragged -offset indent The .Fa dtab @@ -133,7 +132,6 @@ typedef struct _ns_src { u_int32_t flags; } ns_src; .Ed -.Pp .Bd -ragged -offset indent The .Fa defaults @@ -176,6 +174,7 @@ While there is support for arbitrary sources, the following .Bl -column NSSRC_COMPAT compat -offset indent .It Sy "#define value" .It Dv NSSRC_FILES Ta """files"" +.It Dv NSSRC_DB Ta """db"" .It Dv NSSRC_DNS Ta """dns"" .It Dv NSSRC_NIS Ta """nis"" .It Dv NSSRC_COMPAT Ta """compat"" diff --git a/lib/libc/net/nsdispatch.c b/lib/libc/net/nsdispatch.c index 162d592..6b7bd02 100644 --- a/lib/libc/net/nsdispatch.c +++ b/lib/libc/net/nsdispatch.c @@ -707,11 +707,13 @@ _nsdispatch(void *retval, const ns_dtab disp_tab[], const char *database, va_end(ap); } else { cache_flag = 0; + errno = 0; va_start(ap, defaults); result = method(retval, mdata, ap); va_end(ap); } #else /* NS_CACHING */ + errno = 0; va_start(ap, defaults); result = method(retval, mdata, ap); va_end(ap); diff --git a/lib/libc/net/nslexer.l b/lib/libc/net/nslexer.l index 34c79d9..0f705cf 100644 --- a/lib/libc/net/nslexer.l +++ b/lib/libc/net/nslexer.l @@ -53,6 +53,7 @@ static char *rcsid = #include "nsparser.h" +#define YY_NO_INPUT #define YY_NO_UNPUT %} diff --git a/lib/libc/net/sctp_getaddrlen.3 b/lib/libc/net/sctp_getaddrlen.3 index ac7bfb3..762e32d 100644 --- a/lib/libc/net/sctp_getaddrlen.3 +++ b/lib/libc/net/sctp_getaddrlen.3 @@ -51,7 +51,7 @@ The .Fn sctp_getaddrlen function returns the size of a specific address family. This function -is provided for application binary compatability since it +is provided for application binary compatibility since it provides the application with the size the operating system thinks the specific address family is. Note that the function diff --git a/lib/libc/net/sctp_recvmsg.3 b/lib/libc/net/sctp_recvmsg.3 index a5926bf..8ddbeb8 100644 --- a/lib/libc/net/sctp_recvmsg.3 +++ b/lib/libc/net/sctp_recvmsg.3 @@ -88,7 +88,7 @@ will hold the address of the peer and .Fa fromlen will hold the length of that address. Note that -the address is bounded by the inital value of +the address is bounded by the initial value of .Fa fromlen which is used as an in/out variable. .Pp @@ -146,14 +146,14 @@ The argument is defined as follows. .Bd -literal struct sctp_sndrcvinfo { - u_int16_t sinfo_stream; /* Stream arriving on */ - u_int16_t sinfo_ssn; /* Stream Sequence Number */ - u_int16_t sinfo_flags; /* Flags on the incoming message */ - u_int32_t sinfo_ppid; /* The ppid field */ - u_int32_t sinfo_context; /* context field */ - u_int32_t sinfo_timetolive; /* not used by sctp_recvmsg */ - u_int32_t sinfo_tsn; /* The transport sequence number */ - u_int32_t sinfo_cumtsn; /* The cumulative acknowledgment point */ + uint16_t sinfo_stream; /* Stream arriving on */ + uint16_t sinfo_ssn; /* Stream Sequence Number */ + uint16_t sinfo_flags; /* Flags on the incoming message */ + uint32_t sinfo_ppid; /* The ppid field */ + uint32_t sinfo_context; /* context field */ + uint32_t sinfo_timetolive; /* not used by sctp_recvmsg */ + uint32_t sinfo_tsn; /* The transport sequence number */ + uint32_t sinfo_cumtsn; /* The cumulative acknowledgment point */ sctp_assoc_t sinfo_assoc_id; /* The association id of the peer */ }; .Ed @@ -238,7 +238,7 @@ The field is not used by .Fn sctp_recvmsg . .Sh RETURN VALUES -The call returns the number of characters sent, or -1 +The call returns the number of bytes received, or -1 if an error occurred. .Sh ERRORS The diff --git a/lib/libc/net/sctp_send.3 b/lib/libc/net/sctp_send.3 index 8a4142c..9acb616 100644 --- a/lib/libc/net/sctp_send.3 +++ b/lib/libc/net/sctp_send.3 @@ -94,14 +94,14 @@ structure is used to control various SCTP features and has the following format: .Bd -literal struct sctp_sndrcvinfo { - u_int16_t sinfo_stream; /* Stream sending to */ - u_int16_t sinfo_ssn; /* valid for recv only */ - u_int16_t sinfo_flags; /* flags to control sending */ - u_int32_t sinfo_ppid; /* ppid field */ - u_int32_t sinfo_context; /* context field */ - u_int32_t sinfo_timetolive; /* timetolive for PR-SCTP */ - u_int32_t sinfo_tsn; /* valid for recv only */ - u_int32_t sinfo_cumtsn; /* valid for recv only */ + uint16_t sinfo_stream; /* Stream sending to */ + uint16_t sinfo_ssn; /* valid for recv only */ + uint16_t sinfo_flags; /* flags to control sending */ + uint32_t sinfo_ppid; /* ppid field */ + uint32_t sinfo_context; /* context field */ + uint32_t sinfo_timetolive; /* timetolive for PR-SCTP */ + uint32_t sinfo_tsn; /* valid for recv only */ + uint32_t sinfo_cumtsn; /* valid for recv only */ sctp_assoc_t sinfo_assoc_id; /* The association id */ }; .Ed @@ -170,7 +170,7 @@ For a one-to-many type (SOCK_SEQPACKET) socket the flag .Dv SCTP_SENDALL can be used as a convenient way to make one send call and have all associations that are under the socket get a copy of the message. -Note that this mechanism is quite efficent and makes only one actual +Note that this mechanism is quite efficient and makes only one actual copy of the data which is shared by all the associations for sending. .Pp The remaining flags are used for the partial reliability extension (RFC3758) @@ -187,7 +187,7 @@ The .Fa sinfo->sinfo_timetolive argument is then a number of milliseconds for which the data is attempted to be transmitted. -If that many milliseconds ellapse +If that many milliseconds elapse and the peer has not acknowledged the data, the data will be skipped and no longer transmitted. Note that this policy does diff --git a/lib/libc/net/sctp_sendmsg.3 b/lib/libc/net/sctp_sendmsg.3 index c54aaef..ddd88b4 100644 --- a/lib/libc/net/sctp_sendmsg.3 +++ b/lib/libc/net/sctp_sendmsg.3 @@ -72,7 +72,7 @@ Data sent in such an instance will result in the data being sent on the third leg of the SCTP four-way handshake. Note that if the socket is a one-to-one type (SOCK_STREAM) socket then an association must -be in existance (by use of the +be in existence (by use of the .Xr connect 2 system call). Calling @@ -180,9 +180,9 @@ to find the association but also as the actual address to send to. .Pp For a one-to-many type (SOCK_SEQPACKET) socket the flag .Dv SCTP_SENDALL -can be used as a convient way to make one send call and have +can be used as a convenient way to make one send call and have all associations that are under the socket get a copy of the message. -Note that this mechanism is quite efficent and makes only one actual +Note that this mechanism is quite efficient and makes only one actual copy of the data which is shared by all the associations for sending. .Pp The remaining flags are used for the partial reliability extension (RFC3758) @@ -199,7 +199,7 @@ The .Fa timetolive argument is then a number of milliseconds for which the data is attempted to be transmitted. -If that many milliseconds ellapse +If that many milliseconds elapse and the peer has not acknowledged the data, the data will be skipped and no longer transmitted. Note that this policy does diff --git a/lib/libc/net/sctp_sys_calls.c b/lib/libc/net/sctp_sys_calls.c index d876293..0921669 100644 --- a/lib/libc/net/sctp_sys_calls.c +++ b/lib/libc/net/sctp_sys_calls.c @@ -1,33 +1,35 @@ -/* $KAME: sctp_sys_calls.c,v 1.9 2004/08/17 06:08:53 itojun Exp $ */ - -/* - * Copyright (C) 2002-2007 Cisco Systems Inc, - * All rights reserved. +/*- + * Copyright (c) 2001-2007, by Cisco Systems, Inc. All rights reserved. + * Copyright (c) 2008-2011, by Randall Stewart. All rights reserved. + * Copyright (c) 2008-2011, by Michael Tuexen. All rights reserved. * * Redistribution and use in source and binary forms, with or without - * modification, are permitted provided that the following conditions - * are met: - * 1. Redistributions of source code must retain the above copyright - * notice, this list of conditions and the following disclaimer. - * 2. Redistributions in binary form must reproduce the above copyright - * notice, this 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. + * modification, are permitted provided that the following conditions are met: + * + * a) Redistributions of source code must retain the above copyright notice, + * this list of conditions and the following disclaimer. + * + * b) Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in + * the documentation and/or other materials provided with the distribution. * - * 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. + * c) Neither the name of Cisco Systems, Inc. nor the names of its + * 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. */ + #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); #include <stdio.h> @@ -49,16 +51,15 @@ __FBSDID("$FreeBSD$"); #ifndef IN6_IS_ADDR_V4MAPPED #define IN6_IS_ADDR_V4MAPPED(a) \ - ((*(const u_int32_t *)(const void *)(&(a)->s6_addr[0]) == 0) && \ - (*(const u_int32_t *)(const void *)(&(a)->s6_addr[4]) == 0) && \ - (*(const u_int32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) + ((*(const uint32_t *)(const void *)(&(a)->s6_addr[0]) == 0) && \ + (*(const uint32_t *)(const void *)(&(a)->s6_addr[4]) == 0) && \ + (*(const uint32_t *)(const void *)(&(a)->s6_addr[8]) == ntohl(0x0000ffff))) #endif #define SCTP_CONTROL_VEC_SIZE_SND 8192 #define SCTP_CONTROL_VEC_SIZE_RCV 16384 #define SCTP_STACK_BUF_SIZE 2048 -#define SCTP_SMALL_IOVEC_SIZE 2 #ifdef SCTP_DEBUG_PRINT_ADDRESS @@ -304,7 +305,7 @@ sctp_bindx(int sd, struct sockaddr *addrs, int addrcnt, int flags) goto out_error; } - + sa = (struct sockaddr *)((caddr_t)sa + sz); } sa = addrs; /* @@ -398,6 +399,9 @@ sctp_opt_info(int sd, sctp_assoc_t id, int opt, void *arg, socklen_t * size) case SCTP_LOCAL_AUTH_CHUNKS: ((struct sctp_authchunks *)arg)->gauth_assoc_id = id; break; + case SCTP_TIMEOUTS: + ((struct sctp_timeouts *)arg)->stimo_assoc_id = id; + break; default: break; } @@ -533,11 +537,11 @@ sctp_sendmsg(int s, size_t len, const struct sockaddr *to, socklen_t tolen, - u_int32_t ppid, - u_int32_t flags, - u_int16_t stream_no, - u_int32_t timetolive, - u_int32_t context) + uint32_t ppid, + uint32_t flags, + uint16_t stream_no, + uint32_t timetolive, + uint32_t context) { #ifdef SYS_sctp_generic_sendmsg struct sctp_sndrcvinfo sinfo; @@ -551,11 +555,10 @@ sctp_sendmsg(int s, return (syscall(SYS_sctp_generic_sendmsg, s, data, len, to, tolen, &sinfo, 0)); #else - ssize_t sz; struct msghdr msg; struct sctp_sndrcvinfo *s_info; - struct iovec iov[SCTP_SMALL_IOVEC_SIZE]; + struct iovec iov; char controlVector[SCTP_CONTROL_VEC_SIZE_RCV]; struct cmsghdr *cmsg; struct sockaddr *who = NULL; @@ -564,20 +567,8 @@ sctp_sendmsg(int s, struct sockaddr_in6 in6; } addr; -/* - fprintf(io, "sctp_sendmsg(sd:%d, data:%x, len:%d, to:%x, tolen:%d, ppid:%x, flags:%x str:%d ttl:%d ctx:%x\n", - s, - (u_int)data, - (int)len, - (u_int)to, - (int)tolen, - ppid, flags, - (int)stream_no, - (int)timetolive, - (u_int)context); - fflush(io); -*/ - if ((tolen > 0) && ((to == NULL) || (tolen < sizeof(struct sockaddr)))) { + if ((tolen > 0) && + ((to == NULL) || (tolen < sizeof(struct sockaddr)))) { errno = EINVAL; return -1; } @@ -587,7 +578,8 @@ sctp_sendmsg(int s, errno = EINVAL; return -1; } - if ((to->sa_len > 0) && (to->sa_len != sizeof(struct sockaddr_in))) { + if ((to->sa_len > 0) && + (to->sa_len != sizeof(struct sockaddr_in))) { errno = EINVAL; return -1; } @@ -598,7 +590,8 @@ sctp_sendmsg(int s, errno = EINVAL; return -1; } - if ((to->sa_len > 0) && (to->sa_len != sizeof(struct sockaddr_in6))) { + if ((to->sa_len > 0) && + (to->sa_len != sizeof(struct sockaddr_in6))) { errno = EINVAL; return -1; } @@ -610,10 +603,8 @@ sctp_sendmsg(int s, } who = (struct sockaddr *)&addr; } - iov[0].iov_base = (char *)data; - iov[0].iov_len = len; - iov[1].iov_base = NULL; - iov[1].iov_len = 0; + iov.iov_base = (char *)data; + iov.iov_len = len; if (who) { msg.msg_name = (caddr_t)who; @@ -622,7 +613,7 @@ sctp_sendmsg(int s, msg.msg_name = (caddr_t)NULL; msg.msg_namelen = 0; } - msg.msg_iov = iov; + msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = (caddr_t)controlVector; @@ -681,7 +672,7 @@ sctp_send(int sd, const void *data, size_t len, #else ssize_t sz; struct msghdr msg; - struct iovec iov[SCTP_SMALL_IOVEC_SIZE]; + struct iovec iov; struct sctp_sndrcvinfo *s_info; char controlVector[SCTP_CONTROL_VEC_SIZE_SND]; struct cmsghdr *cmsg; @@ -690,14 +681,12 @@ sctp_send(int sd, const void *data, size_t len, errno = EINVAL; return (-1); } - iov[0].iov_base = (char *)data; - iov[0].iov_len = len; - iov[1].iov_base = NULL; - iov[1].iov_len = 0; + iov.iov_base = (char *)data; + iov.iov_len = len; msg.msg_name = 0; msg.msg_namelen = 0; - msg.msg_iov = iov; + msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = (caddr_t)controlVector; @@ -724,6 +713,7 @@ sctp_sendx(int sd, const void *msg, size_t msg_len, struct sctp_sndrcvinfo *sinfo, int flags) { + struct sctp_sndrcvinfo __sinfo; ssize_t ret; int i, cnt, *aa, saved_errno; char *buf; @@ -735,7 +725,7 @@ sctp_sendx(int sd, const void *msg, size_t msg_len, return (-1); } #ifdef SYS_sctp_generic_sendmsg - if (addrcnt < SCTP_SMALL_IOVEC_SIZE) { + if (addrcnt == 1) { socklen_t l; /* @@ -790,6 +780,10 @@ sctp_sendx(int sd, const void *msg, size_t msg_len, return (ret); } continue_send: + if (sinfo == NULL) { + sinfo = &__sinfo; + memset(&__sinfo, 0, sizeof(__sinfo)); + } sinfo->sinfo_assoc_id = sctp_getassocid(sd, addrs); if (sinfo->sinfo_assoc_id == 0) { printf("Huh, can't get associd? TSNH!\n"); @@ -814,11 +808,11 @@ sctp_sendmsgx(int sd, size_t len, struct sockaddr *addrs, int addrcnt, - u_int32_t ppid, - u_int32_t flags, - u_int16_t stream_no, - u_int32_t timetolive, - u_int32_t context) + uint32_t ppid, + uint32_t flags, + uint16_t stream_no, + uint32_t timetolive, + uint32_t context) { struct sctp_sndrcvinfo sinfo; @@ -841,18 +835,18 @@ sctp_recvmsg(int s, int *msg_flags) { #ifdef SYS_sctp_generic_recvmsg - struct iovec iov[SCTP_SMALL_IOVEC_SIZE]; + struct iovec iov; - iov[0].iov_base = dbuf; - iov[0].iov_len = len; + iov.iov_base = dbuf; + iov.iov_len = len; return (syscall(SYS_sctp_generic_recvmsg, s, - iov, 1, from, fromlen, sinfo, msg_flags)); + &iov, 1, from, fromlen, sinfo, msg_flags)); #else struct sctp_sndrcvinfo *s_info; ssize_t sz; int sinfo_found = 0; struct msghdr msg; - struct iovec iov[SCTP_SMALL_IOVEC_SIZE]; + struct iovec iov; char controlVector[SCTP_CONTROL_VEC_SIZE_RCV]; struct cmsghdr *cmsg; @@ -861,30 +855,28 @@ sctp_recvmsg(int s, return (-1); } msg.msg_flags = 0; - iov[0].iov_base = dbuf; - iov[0].iov_len = len; - iov[1].iov_base = NULL; - iov[1].iov_len = 0; + iov.iov_base = dbuf; + iov.iov_len = len; msg.msg_name = (caddr_t)from; if (fromlen == NULL) msg.msg_namelen = 0; else msg.msg_namelen = *fromlen; - msg.msg_iov = iov; + msg.msg_iov = &iov; msg.msg_iovlen = 1; msg.msg_control = (caddr_t)controlVector; msg.msg_controllen = sizeof(controlVector); errno = 0; sz = recvmsg(s, &msg, *msg_flags); - if (sz <= 0) + *msg_flags = msg.msg_flags; + if (sz <= 0) { return (sz); - + } s_info = NULL; len = sz; - *msg_flags = msg.msg_flags; - if (sinfo) + if (sinfo) { sinfo->sinfo_assoc_id = 0; - + } if ((msg.msg_controllen) && sinfo) { /* * parse through and see if we find the sctp_sndrcvinfo (if @@ -935,7 +927,7 @@ int sctp_peeloff(int sd, sctp_assoc_t assoc_id) { struct sctp_peeloff_opt peeloff; - int error; + int result; socklen_t optlen; /* set in the socket option params */ @@ -943,10 +935,9 @@ sctp_peeloff(int sd, sctp_assoc_t assoc_id) peeloff.s = sd; peeloff.assoc_id = assoc_id; optlen = sizeof(peeloff); - error = getsockopt(sd, IPPROTO_SCTP, SCTP_PEELOFF, (void *)&peeloff, - &optlen); - if (error) { - errno = error; + result = getsockopt(sd, IPPROTO_SCTP, SCTP_PEELOFF, (void *)&peeloff, &optlen); + + if (result < 0) { return (-1); } else { return (peeloff.new_sd); @@ -979,4 +970,3 @@ sctp_peeloff(int sd, sctp_assoc_t assoc_id) #undef SCTP_CONTROL_VEC_SIZE_SND #undef SCTP_CONTROL_VEC_SIZE_RCV #undef SCTP_STACK_BUF_SIZE -#undef SCTP_SMALL_IOVEC_SIZE diff --git a/lib/libc/nls/ru_RU.KOI8-R.msg b/lib/libc/nls/ru_RU.KOI8-R.msg index 431bc27..48bc1d4 100644 --- a/lib/libc/nls/ru_RU.KOI8-R.msg +++ b/lib/libc/nls/ru_RU.KOI8-R.msg @@ -183,6 +183,16 @@ $ ENOATTR 87 áÔÒÉÂÕÔ ÎÅ ÎÁÊÄÅÎ $ EDOOFUS 88 ïÛÉÂËÁ ÐÒÏÇÒÁÍÍÉÒÏ×ÁÎÉÑ +$ EBADMSG +89 ðÌÏÈÏÊ ÆÏÒÍÁÔ ÓÏÏÂÝÅÎÉÑ +$ EMULTIHOP +90 ðÏÐÙÔËÁ ÍÕÌØÔÉÈÏÐÁ +$ ENOLINK +91 ëÁÎÁÌ ÒÁÚÏÒ×ÁÎ +$ EPROTO +92 ïÛÉÂËÁ ÐÒÏÔÏËÏÌÁ +$ ENOTCAPABLE +93 îÅÄÏÓÔÁÔÏÞÎÏ ×ÏÚÍÏÖÎÏÓÔÅÊ $ $ strsignal() support catalog $ diff --git a/lib/libc/posix1e/Makefile.inc b/lib/libc/posix1e/Makefile.inc index 30e3986..c9d3ba5 100644 --- a/lib/libc/posix1e/Makefile.inc +++ b/lib/libc/posix1e/Makefile.inc @@ -20,6 +20,7 @@ SRCS+= acl_branding.c \ acl_from_text.c \ acl_from_text_nfs4.c \ acl_get.c \ + acl_id_to_name.c \ acl_init.c \ acl_perm.c \ acl_set.c \ diff --git a/lib/libc/posix1e/acl_add_flag_np.3 b/lib/libc/posix1e/acl_add_flag_np.3 index 3acde6b..7ae83e2 100644 --- a/lib/libc/posix1e/acl_add_flag_np.3 +++ b/lib/libc/posix1e/acl_add_flag_np.3 @@ -51,7 +51,6 @@ Note: it is not considered an error to attempt to add flags that already exist in the flagset. .Pp Valid values are: -.Pp .Bl -column -offset 3n "ACL_ENTRY_NO_PROPAGATE_INHERIT" .It ACL_ENTRY_FILE_INHERIT Will be inherited by files. .It ACL_ENTRY_DIRECTORY_INHERIT Will be inherited by directories. diff --git a/lib/libc/posix1e/acl_add_perm.3 b/lib/libc/posix1e/acl_add_perm.3 index 336e55e..beb5f98 100644 --- a/lib/libc/posix1e/acl_add_perm.3 +++ b/lib/libc/posix1e/acl_add_perm.3 @@ -51,7 +51,6 @@ Note: it is not considered an error to attempt to add permissions that already exist in the permission set. .Pp For POSIX.1e ACLs, valid values are: -.Pp .Bl -column -offset 3n "ACL_WRITE_NAMED_ATTRS" .It ACL_EXECUTE Execute permission .It ACL_WRITE Write permission @@ -59,7 +58,6 @@ For POSIX.1e ACLs, valid values are: .El .Pp For NFSv4 ACLs, valid values are: -.Pp .Bl -column -offset 3n "ACL_WRITE_NAMED_ATTRS" .It ACL_READ_DATA Read permission .It ACL_LIST_DIRECTORY Same as ACL_READ_DATA diff --git a/lib/libc/posix1e/acl_branding.c b/lib/libc/posix1e/acl_branding.c index 9839477..84b0063 100644 --- a/lib/libc/posix1e/acl_branding.c +++ b/lib/libc/posix1e/acl_branding.c @@ -129,6 +129,9 @@ _acl_type_not_valid_for_acl(const acl_t acl, acl_type_t type) if (type == ACL_TYPE_ACCESS || type == ACL_TYPE_DEFAULT) return (0); break; + + case ACL_BRAND_UNKNOWN: + return (0); } return (-1); diff --git a/lib/libc/posix1e/acl_entry.c b/lib/libc/posix1e/acl_entry.c index 56396f9..3f8ca62 100644 --- a/lib/libc/posix1e/acl_entry.c +++ b/lib/libc/posix1e/acl_entry.c @@ -55,8 +55,7 @@ acl_create_entry(acl_t *acl_p, acl_entry_t *entry_p) * +1, because we are checking if there is space left for one more * entry. */ - if ((acl_int->acl_cnt + 1 >= ACL_MAX_ENTRIES) || - (acl_int->acl_cnt < 0)) { + if (acl_int->acl_cnt + 1 >= ACL_MAX_ENTRIES) { errno = EINVAL; return (-1); } @@ -87,7 +86,7 @@ acl_create_entry_np(acl_t *acl_p, acl_entry_t *entry_p, int offset) acl_int = &(*acl_p)->ats_acl; - if ((acl_int->acl_cnt + 1 >= ACL_MAX_ENTRIES) || (acl_int->acl_cnt < 0)) { + if (acl_int->acl_cnt + 1 >= ACL_MAX_ENTRIES) { errno = EINVAL; return (-1); } diff --git a/lib/libc/posix1e/acl_from_text.c b/lib/libc/posix1e/acl_from_text.c index c600987..7f15463 100644 --- a/lib/libc/posix1e/acl_from_text.c +++ b/lib/libc/posix1e/acl_from_text.c @@ -44,7 +44,6 @@ __FBSDID("$FreeBSD$"); #include "acl_support.h" -static int _posix1e_acl_name_to_id(acl_tag_t tag, char *name, uid_t *id); static acl_tag_t acl_string_to_tag(char *tag, char *qualifier); int _nfs4_acl_entry_from_text(acl_t aclp, char *entry); @@ -148,8 +147,7 @@ _posix1e_acl_entry_from_text(acl_t aclp, char *entry) case ACL_USER: case ACL_GROUP: - error = _posix1e_acl_name_to_id(t, qualifier, - &id); + error = _acl_name_to_id(t, qualifier, &id); if (error == -1) return (-1); break; @@ -271,12 +269,9 @@ error_label: * XXX NOT THREAD SAFE, RELIES ON GETPWNAM, GETGRNAM * XXX USES *PW* AND *GR* WHICH ARE STATEFUL AND THEREFORE THIS ROUTINE * MAY HAVE SIDE-EFFECTS - * - * XXX currently doesn't deal correctly with a numeric uid being passed - * instead of a username. What is correct behavior here? Check chown. */ -static int -_posix1e_acl_name_to_id(acl_tag_t tag, char *name, uid_t *id) +int +_acl_name_to_id(acl_tag_t tag, char *name, uid_t *id) { struct group *g; struct passwd *p; diff --git a/lib/libc/posix1e/acl_from_text_nfs4.c b/lib/libc/posix1e/acl_from_text_nfs4.c index 12bfb4e..5a0b36a 100644 --- a/lib/libc/posix1e/acl_from_text_nfs4.c +++ b/lib/libc/posix1e/acl_from_text_nfs4.c @@ -79,16 +79,14 @@ parse_tag(const char *str, acl_entry_t entry, int *need_qualifier) /* * Parse the qualifier field of ACL entry passed as "str". * If user or group name cannot be resolved, then the variable - * referenced by "need_qualifier" is set to 1. + * referenced by "need_qualifier" is set to 1; it will be checked + * later to figure out whether the appended_id is required. */ static int parse_qualifier(char *str, acl_entry_t entry, int *need_qualifier) { int qualifier_length, error; - id_t id; - char *end; - struct passwd *pwd; - struct group *grp; + uid_t id; acl_tag_t tag; assert(need_qualifier != NULL); @@ -101,44 +99,17 @@ parse_qualifier(char *str, acl_entry_t entry, int *need_qualifier) return (-1); } - /* XXX: Can we assume that valid username never begins with a digit? */ - if (isdigit(str[0])) { - id = strtod(str, &end); - - if (end - str != qualifier_length) { - warnx("malformed ACL: trailing characters " - "after numerical id"); - return (-1); - } - - return (acl_set_qualifier(entry, &id)); - } - error = acl_get_tag_type(entry, &tag); if (error) return (error); - assert(tag == ACL_USER || tag == ACL_GROUP); - - if (tag == ACL_USER) { - /* XXX: Thread-unsafe. */ - pwd = getpwnam(str); - if (pwd == NULL) { - *need_qualifier = 1; - return (0); - } - - return (acl_set_qualifier(entry, &(pwd->pw_uid))); - } - - /* XXX: Thread-unsafe. */ - grp = getgrnam(str); - if (grp == NULL) { + error = _acl_name_to_id(tag, str, &id); + if (error) { *need_qualifier = 1; return (0); } - return (acl_set_qualifier(entry, &(grp->gr_gid))); + return (acl_set_qualifier(entry, &id)); } static int diff --git a/lib/libc/posix1e/acl_get.3 b/lib/libc/posix1e/acl_get.3 index 651709f..ae0c48d 100644 --- a/lib/libc/posix1e/acl_get.3 +++ b/lib/libc/posix1e/acl_get.3 @@ -95,7 +95,6 @@ decisions. Valid values for the .Va type argument are: -.Pp .Bl -column -offset 3n "ACL_TYPE_DEFAULT" .It ACL_TYPE_ACCESS POSIX.1e access ACL .It ACL_TYPE_DEFAULT POSIX.1e default ACL diff --git a/lib/libc/posix1e/acl_get.c b/lib/libc/posix1e/acl_get.c index 8a77ab1..b323501 100644 --- a/lib/libc/posix1e/acl_get.c +++ b/lib/libc/posix1e/acl_get.c @@ -132,30 +132,6 @@ acl_get_fd_np(int fd, acl_type_t type) return (aclp); } -int -acl_get_perm_np(acl_permset_t permset_d, acl_perm_t perm) -{ - - if (permset_d == NULL) { - errno = EINVAL; - return (-1); - } - - switch(perm) { - case ACL_READ: - case ACL_WRITE: - case ACL_EXECUTE: - if (*permset_d & perm) - return (1); - break; - default: - errno = EINVAL; - return (-1); - } - - return (0); -} - /* * acl_get_permset() (23.4.17): return via permset_p a descriptor to * the permission set in the ACL entry entry_d. diff --git a/lib/libc/posix1e/acl_id_to_name.c b/lib/libc/posix1e/acl_id_to_name.c new file mode 100644 index 0000000..aa10809 --- /dev/null +++ b/lib/libc/posix1e/acl_id_to_name.c @@ -0,0 +1,100 @@ +/*- + * Copyright (c) 1999-2001, 2008 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. + */ +/* + * Support functionality for the POSIX.1e ACL interface + * These calls are intended only to be called within the library. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#include <sys/types.h> +#include "namespace.h" +#include <sys/acl.h> +#include "un-namespace.h" +#include <errno.h> +#include <grp.h> +#include <pwd.h> +#include <stdio.h> +#include <stdlib.h> +#include <string.h> +#include <assert.h> + +#include "acl_support.h" + +/* + * Given a uid/gid, return a username/groupname for the text form of an ACL. + * Note that we truncate user and group names, rather than error out, as + * this is consistent with other tools manipulating user and group names. + * XXX NOT THREAD SAFE, RELIES ON GETPWUID, GETGRGID + * XXX USES *PW* AND *GR* WHICH ARE STATEFUL AND THEREFORE THIS ROUTINE + * MAY HAVE SIDE-EFFECTS + */ +int +_posix1e_acl_id_to_name(acl_tag_t tag, uid_t id, ssize_t buf_len, char *buf, + int flags) +{ + struct group *g; + struct passwd *p; + int i; + + switch(tag) { + case ACL_USER: + if (flags & ACL_TEXT_NUMERIC_IDS) + p = NULL; + else + p = getpwuid(id); + if (!p) + i = snprintf(buf, buf_len, "%d", id); + else + i = snprintf(buf, buf_len, "%s", p->pw_name); + + if (i < 0) { + errno = ENOMEM; + return (-1); + } + return (0); + + case ACL_GROUP: + if (flags & ACL_TEXT_NUMERIC_IDS) + g = NULL; + else + g = getgrgid(id); + if (g == NULL) + i = snprintf(buf, buf_len, "%d", id); + else + i = snprintf(buf, buf_len, "%s", g->gr_name); + + if (i < 0) { + errno = ENOMEM; + return (-1); + } + return (0); + + default: + return (EINVAL); + } +} diff --git a/lib/libc/posix1e/acl_is_trivial_np.3 b/lib/libc/posix1e/acl_is_trivial_np.3 index 787e3f9..4ad1a63 100644 --- a/lib/libc/posix1e/acl_is_trivial_np.3 +++ b/lib/libc/posix1e/acl_is_trivial_np.3 @@ -27,7 +27,7 @@ .\" .\" $FreeBSD$ .\" -.Dd June 25, 2009 +.Dd December 13, 2010 .Dt ACL_STRIP_NP 3 .Os .Sh NAME @@ -56,7 +56,9 @@ ACL is trivial if it can be fully expressed as a file mode without loosing any access rules. For POSIX.1e ACLs, ACL is trivial if it has the three required entries, one for owner, one for owning group, and one for other. -For NFSv4 ACLs, ACL is trivial if it has the "canonical six" entries. +For NFSv4 ACLs, ACL is trivial if is identical to the ACL generated by +.Fn acl_strip_np 3 +from the file mode. Files that have non-trivial ACL have a plus sign appended after mode bits in "ls -l" output. .Sh RETURN VALUES diff --git a/lib/libc/posix1e/acl_perm.c b/lib/libc/posix1e/acl_perm.c index 37d29d6..ad2f47e 100644 --- a/lib/libc/posix1e/acl_perm.c +++ b/lib/libc/posix1e/acl_perm.c @@ -35,6 +35,20 @@ __FBSDID("$FreeBSD$"); #include <errno.h> #include <string.h> +static int +_perm_is_invalid(acl_perm_t perm) +{ + + /* Check if more than a single bit is set. */ + if ((perm & -perm) == perm && + (perm & (ACL_POSIX1E_BITS | ACL_NFS4_PERM_BITS)) == perm) + return (0); + + errno = EINVAL; + + return (1); +} + /* * acl_add_perm() (23.4.1): add the permission contained in perm to the * permission set permset_d @@ -43,18 +57,17 @@ int acl_add_perm(acl_permset_t permset_d, acl_perm_t perm) { - if (permset_d) { - switch(perm) { - case ACL_READ: - case ACL_WRITE: - case ACL_EXECUTE: - *permset_d |= perm; - return (0); - } + if (permset_d == NULL) { + errno = EINVAL; + return (-1); } - errno = EINVAL; - return (-1); + if (_perm_is_invalid(perm)) + return (-1); + + *permset_d |= perm; + + return (0); } /* @@ -83,16 +96,33 @@ int acl_delete_perm(acl_permset_t permset_d, acl_perm_t perm) { - if (permset_d) { - switch(perm) { - case ACL_READ: - case ACL_WRITE: - case ACL_EXECUTE: - *permset_d &= ~(perm & ACL_PERM_BITS); - return (0); - } + if (permset_d == NULL) { + errno = EINVAL; + return (-1); } - errno = EINVAL; - return (-1); + if (_perm_is_invalid(perm)) + return (-1); + + *permset_d &= ~perm; + + return (0); +} + +int +acl_get_perm_np(acl_permset_t permset_d, acl_perm_t perm) +{ + + if (permset_d == NULL) { + errno = EINVAL; + return (-1); + } + + if (_perm_is_invalid(perm)) + return (-1); + + if (*permset_d & perm) + return (1); + + return (0); } diff --git a/lib/libc/posix1e/acl_set.3 b/lib/libc/posix1e/acl_set.3 index a6134fe..7450dc9 100644 --- a/lib/libc/posix1e/acl_set.3 +++ b/lib/libc/posix1e/acl_set.3 @@ -79,7 +79,6 @@ path is a symlink. Valid values for the .Va type argument are: -.Pp .Bl -column -offset 3n "ACL_TYPE_DEFAULT" .It ACL_TYPE_ACCESS POSIX.1e access ACL .It ACL_TYPE_DEFAULT POSIX.1e default ACL diff --git a/lib/libc/posix1e/acl_set.c b/lib/libc/posix1e/acl_set.c index f9ee76d..fdc12b6 100644 --- a/lib/libc/posix1e/acl_set.c +++ b/lib/libc/posix1e/acl_set.c @@ -53,7 +53,6 @@ __FBSDID("$FreeBSD$"); int acl_set_file(const char *path_p, acl_type_t type, acl_t acl) { - int error; if (acl == NULL || path_p == NULL) { errno = EINVAL; @@ -64,13 +63,8 @@ acl_set_file(const char *path_p, acl_type_t type, acl_t acl) errno = EINVAL; return (-1); } - if (_posix1e_acl(acl, type)) { - error = _posix1e_acl_sort(acl); - if (error) { - errno = error; - return (-1); - } - } + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); acl->ats_cur_entry = 0; @@ -80,7 +74,6 @@ acl_set_file(const char *path_p, acl_type_t type, acl_t acl) int acl_set_link_np(const char *path_p, acl_type_t type, acl_t acl) { - int error; if (acl == NULL || path_p == NULL) { errno = EINVAL; @@ -91,13 +84,8 @@ acl_set_link_np(const char *path_p, acl_type_t type, acl_t acl) errno = EINVAL; return (-1); } - if (_posix1e_acl(acl, type)) { - error = _posix1e_acl_sort(acl); - if (error) { - errno = error; - return (-1); - } - } + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); acl->ats_cur_entry = 0; @@ -117,7 +105,6 @@ acl_set_fd(int fd, acl_t acl) int acl_set_fd_np(int fd, acl_t acl, acl_type_t type) { - int error; if (acl == NULL) { errno = EINVAL; @@ -128,13 +115,8 @@ acl_set_fd_np(int fd, acl_t acl, acl_type_t type) errno = EINVAL; return (-1); } - if (_posix1e_acl(acl, type)) { - error = _posix1e_acl_sort(acl); - if (error) { - errno = error; - return (-1); - } - } + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); acl->ats_cur_entry = 0; diff --git a/lib/libc/posix1e/acl_set_entry_type_np.3 b/lib/libc/posix1e/acl_set_entry_type_np.3 index 9f69bab..bda0c48 100644 --- a/lib/libc/posix1e/acl_set_entry_type_np.3 +++ b/lib/libc/posix1e/acl_set_entry_type_np.3 @@ -48,7 +48,6 @@ to the value referred to by .Fa entry_type . .Pp Valid values are: -.Pp .Bl -column -offset 3n "ACL_ENTRY_TYPE_ALLOW" .It ACL_ENTRY_TYPE_ALLOW "allow" type entry .It ACL_ENTRY_TYPE_DENY "deny" type entry diff --git a/lib/libc/posix1e/acl_set_tag_type.3 b/lib/libc/posix1e/acl_set_tag_type.3 index 2568922..88aad72 100644 --- a/lib/libc/posix1e/acl_set_tag_type.3 +++ b/lib/libc/posix1e/acl_set_tag_type.3 @@ -48,7 +48,6 @@ to the value of .Fa tag_type . .Pp Valid values are: -.Pp .Bl -column -offset 3n "ACL_OTHER_OBJ" .It ACL_USER_OBJ Permissions apply to file owner .It ACL_USER Permissions apply to additional user specified by qualifier diff --git a/lib/libc/posix1e/acl_strip.c b/lib/libc/posix1e/acl_strip.c index 1dcdfcd..ae37b38 100644 --- a/lib/libc/posix1e/acl_strip.c +++ b/lib/libc/posix1e/acl_strip.c @@ -14,14 +14,14 @@ * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR THE VOICES IN HIS HEAD BE - * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR - * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF - * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS - * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN - * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) - * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE - * POSSIBILITY OF SUCH DAMAGE. + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY + * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF + * SUCH DAMAGE. */ #include <sys/cdefs.h> @@ -31,22 +31,23 @@ __FBSDID("$FreeBSD$"); #include <stdio.h> #include <assert.h> #include <sys/acl.h> +#include <sys/stat.h> #include "acl_support.h" /* - * These two routines from sys/kern/subr_acl_nfs4.c are used by both kernel + * These routines from sys/kern/subr_acl_nfs4.c are used by both kernel * and libc. */ -void acl_nfs4_sync_acl_from_mode(struct acl *aclp, mode_t mode, - int file_owner_id); void acl_nfs4_sync_mode_from_acl(mode_t *_mode, const struct acl *aclp); +void acl_nfs4_trivial_from_mode_libc(struct acl *aclp, int file_owner_id, + int canonical_six); static acl_t -_nfs4_acl_strip_np(const acl_t aclp, int recalculate_mask) +_nfs4_acl_strip_np(const acl_t aclp, int canonical_six) { acl_t newacl; - mode_t mode; + mode_t mode = 0; newacl = acl_init(ACL_MAX_ENTRIES); if (newacl == NULL) { @@ -57,7 +58,7 @@ _nfs4_acl_strip_np(const acl_t aclp, int recalculate_mask) _acl_brand_as(newacl, ACL_BRAND_NFS4); acl_nfs4_sync_mode_from_acl(&mode, &(aclp->ats_acl)); - acl_nfs4_sync_acl_from_mode(&(newacl->ats_acl), mode, -1); + acl_nfs4_trivial_from_mode_libc(&(newacl->ats_acl), mode, canonical_six); return (newacl); } @@ -136,7 +137,7 @@ acl_strip_np(const acl_t aclp, int recalculate_mask) { switch (_acl_brand(aclp)) { case ACL_BRAND_NFS4: - return (_nfs4_acl_strip_np(aclp, recalculate_mask)); + return (_nfs4_acl_strip_np(aclp, 0)); case ACL_BRAND_POSIX: return (_posix1e_acl_strip_np(aclp, recalculate_mask)); @@ -176,10 +177,34 @@ acl_is_trivial_np(const acl_t aclp, int *trivialp) case ACL_BRAND_NFS4: /* - * Calculate trivial ACL - using acl_strip_np - and compare + * If the ACL has more than canonical six entries, + * it's non trivial by definition. + */ + if (aclp->ats_acl.acl_cnt > 6) { + *trivialp = 0; + return (0); + } + + /* + * Calculate trivial ACL - using acl_strip_np(3) - and compare * with the original. */ - tmpacl = acl_strip_np(aclp, 0); + tmpacl = _nfs4_acl_strip_np(aclp, 0); + if (tmpacl == NULL) + return (-1); + + differs = _acl_differs(aclp, tmpacl); + acl_free(tmpacl); + + if (differs == 0) { + *trivialp = 1; + return (0); + } + + /* + * Try again with an old-style, "canonical six" trivial ACL. + */ + tmpacl = _nfs4_acl_strip_np(aclp, 1); if (tmpacl == NULL) return (-1); diff --git a/lib/libc/posix1e/acl_strip_np.3 b/lib/libc/posix1e/acl_strip_np.3 index 7b3537d..cc6c65b 100644 --- a/lib/libc/posix1e/acl_strip_np.3 +++ b/lib/libc/posix1e/acl_strip_np.3 @@ -32,7 +32,7 @@ .Os .Sh NAME .Nm acl_strip_np -.Nd strip exteneded entries from an ACL +.Nd strip extended entries from an ACL .Sh LIBRARY .Lb libc .Sh SYNOPSIS diff --git a/lib/libc/posix1e/acl_support.c b/lib/libc/posix1e/acl_support.c index 680debc..9f5404c 100644 --- a/lib/libc/posix1e/acl_support.c +++ b/lib/libc/posix1e/acl_support.c @@ -127,11 +127,9 @@ _posix1e_acl_entry_compare(struct acl_entry *a, struct acl_entry *b) } /* - * _posix1e_acl_sort -- sort ACL entries in POSIX.1e-formatted ACLs - * Give the opportunity to fail, although we don't currently have a way - * to fail. + * _posix1e_acl_sort -- sort ACL entries in POSIX.1e-formatted ACLs. */ -int +void _posix1e_acl_sort(acl_t acl) { struct acl *acl_int; @@ -140,8 +138,6 @@ _posix1e_acl_sort(acl_t acl) qsort(&acl_int->acl_entry[0], acl_int->acl_cnt, sizeof(struct acl_entry), (compare) _posix1e_acl_entry_compare); - - return (0); } /* @@ -273,61 +269,6 @@ _posix1e_acl_check(acl_t acl) return (0); } - -/* - * Given a uid/gid, return a username/groupname for the text form of an ACL. - * Note that we truncate user and group names, rather than error out, as - * this is consistent with other tools manipulating user and group names. - * XXX NOT THREAD SAFE, RELIES ON GETPWUID, GETGRGID - * XXX USES *PW* AND *GR* WHICH ARE STATEFUL AND THEREFORE THIS ROUTINE - * MAY HAVE SIDE-EFFECTS - */ -int -_posix1e_acl_id_to_name(acl_tag_t tag, uid_t id, ssize_t buf_len, char *buf, - int flags) -{ - struct group *g; - struct passwd *p; - int i; - - switch(tag) { - case ACL_USER: - if (flags & ACL_TEXT_NUMERIC_IDS) - p = NULL; - else - p = getpwuid(id); - if (!p) - i = snprintf(buf, buf_len, "%d", id); - else - i = snprintf(buf, buf_len, "%s", p->pw_name); - - if (i < 0) { - errno = ENOMEM; - return (-1); - } - return (0); - - case ACL_GROUP: - if (flags & ACL_TEXT_NUMERIC_IDS) - g = NULL; - else - g = getgrgid(id); - if (g == NULL) - i = snprintf(buf, buf_len, "%d", id); - else - i = snprintf(buf, buf_len, "%s", g->gr_name); - - if (i < 0) { - errno = ENOMEM; - return (-1); - } - return (0); - - default: - return (EINVAL); - } -} - /* * Given a right-shifted permission (i.e., direct ACL_PERM_* mask), fill * in a string describing the permissions. diff --git a/lib/libc/posix1e/acl_support.h b/lib/libc/posix1e/acl_support.h index 9826577..11fa29b 100644 --- a/lib/libc/posix1e/acl_support.h +++ b/lib/libc/posix1e/acl_support.h @@ -50,7 +50,7 @@ int _nfs4_format_access_mask(char *str, size_t size, acl_perm_t var, int verbose int _nfs4_parse_flags(const char *str, acl_flag_t *var); int _nfs4_parse_access_mask(const char *str, acl_perm_t *var); int _posix1e_acl_check(acl_t acl); -int _posix1e_acl_sort(acl_t acl); +void _posix1e_acl_sort(acl_t acl); int _posix1e_acl(acl_t acl, acl_type_t type); int _posix1e_acl_id_to_name(acl_tag_t tag, uid_t id, ssize_t buf_len, char *buf, int flags); @@ -61,5 +61,6 @@ int _posix1e_acl_add_entry(acl_t acl, acl_tag_t tag, uid_t id, acl_perm_t perm); char *string_skip_whitespace(char *string); void string_trim_trailing_whitespace(char *string); +int _acl_name_to_id(acl_tag_t tag, char *name, uid_t *id); #endif diff --git a/lib/libc/posix1e/acl_support_nfs4.c b/lib/libc/posix1e/acl_support_nfs4.c index c5be3d1..4878b43 100644 --- a/lib/libc/posix1e/acl_support_nfs4.c +++ b/lib/libc/posix1e/acl_support_nfs4.c @@ -70,6 +70,10 @@ struct flagnames_struct a_access_masks[] = { ACL_WRITE_ACL, "write_acl", 'C'}, { ACL_WRITE_OWNER, "write_owner", 'o'}, { ACL_SYNCHRONIZE, "synchronize", 's'}, + { ACL_FULL_SET, "full_set", '\0'}, + { ACL_MODIFY_SET, "modify_set", '\0'}, + { ACL_READ_SET, "read_set", '\0'}, + { ACL_WRITE_SET, "write_set", '\0'}, { 0, 0, 0}}; static const char * @@ -117,7 +121,7 @@ format_flags_compact(char *str, size_t size, uint32_t var, { size_t i; - for (i = 0; flags[i].name != NULL; i++) { + for (i = 0; flags[i].letter != '\0'; i++) { assert(i < size); if ((flags[i].flag & var) == 0) str[i] = '-'; diff --git a/lib/libc/posix1e/acl_to_text_nfs4.c b/lib/libc/posix1e/acl_to_text_nfs4.c index 3adbfb4..f9945ab 100644 --- a/lib/libc/posix1e/acl_to_text_nfs4.c +++ b/lib/libc/posix1e/acl_to_text_nfs4.c @@ -50,7 +50,7 @@ format_who(char *str, size_t size, const acl_entry_t entry, int numeric) acl_tag_t tag; struct passwd *pwd; struct group *grp; - id_t *id; + uid_t *id; error = acl_get_tag_type(entry, &tag); if (error) @@ -62,7 +62,7 @@ format_who(char *str, size_t size, const acl_entry_t entry, int numeric) break; case ACL_USER: - id = (id_t *)acl_get_qualifier(entry); + id = (uid_t *)acl_get_qualifier(entry); if (id == NULL) return (-1); /* XXX: Thread-unsafe. */ @@ -81,7 +81,7 @@ format_who(char *str, size_t size, const acl_entry_t entry, int numeric) break; case ACL_GROUP: - id = (id_t *)acl_get_qualifier(entry); + id = (uid_t *)acl_get_qualifier(entry); if (id == NULL) return (-1); /* XXX: Thread-unsafe. */ @@ -141,7 +141,7 @@ format_additional_id(char *str, size_t size, const acl_entry_t entry) { int error; acl_tag_t tag; - id_t *id; + uid_t *id; error = acl_get_tag_type(entry, &tag); if (error) @@ -155,7 +155,7 @@ format_additional_id(char *str, size_t size, const acl_entry_t entry) break; default: - id = (id_t *)acl_get_qualifier(entry); + id = (uid_t *)acl_get_qualifier(entry); if (id == NULL) return (-1); snprintf(str, size, ":%d", (unsigned int)*id); @@ -167,7 +167,7 @@ format_additional_id(char *str, size_t size, const acl_entry_t entry) static int format_entry(char *str, size_t size, const acl_entry_t entry, int flags) { - size_t off = 0, padding_length, maximum_who_field_length = 18; + size_t off = 0, min_who_field_length = 18; acl_permset_t permset; acl_flagset_t flagset; int error, len; @@ -188,12 +188,9 @@ format_entry(char *str, size_t size, const acl_entry_t entry, int flags) if (error) return (error); len = strlen(buf); - padding_length = maximum_who_field_length - len; - if (padding_length > 0) { - memset(str, ' ', padding_length); - off += padding_length; - } - off += snprintf(str + off, size - off, "%s:", buf); + if (len < min_who_field_length) + len = min_who_field_length; + off += snprintf(str + off, size - off, "%*s:", len, buf); error = _nfs4_format_access_mask(buf, sizeof(buf), *permset, flags & ACL_TEXT_VERBOSE); @@ -249,6 +246,7 @@ _nfs4_acl_to_text_np(const acl_t aclp, ssize_t *len_p, int flags) error = format_entry(str + off, size - off, entry, flags); if (error) { + free(str); errno = EINVAL; return (NULL); } diff --git a/lib/libc/posix1e/acl_valid.c b/lib/libc/posix1e/acl_valid.c index f345c01..d4cb872 100644 --- a/lib/libc/posix1e/acl_valid.c +++ b/lib/libc/posix1e/acl_valid.c @@ -79,20 +79,14 @@ acl_valid(acl_t acl) int acl_valid_file_np(const char *pathp, acl_type_t type, acl_t acl) { - int error; if (pathp == NULL || acl == NULL) { errno = EINVAL; return (-1); } type = _acl_type_unold(type); - if (_posix1e_acl(acl, type)) { - error = _posix1e_acl_sort(acl); - if (error) { - errno = error; - return (-1); - } - } + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); return (__acl_aclcheck_file(pathp, type, &acl->ats_acl)); } @@ -100,20 +94,14 @@ acl_valid_file_np(const char *pathp, acl_type_t type, acl_t acl) int acl_valid_link_np(const char *pathp, acl_type_t type, acl_t acl) { - int error; if (pathp == NULL || acl == NULL) { errno = EINVAL; return (-1); } type = _acl_type_unold(type); - if (_posix1e_acl(acl, type)) { - error = _posix1e_acl_sort(acl); - if (error) { - errno = error; - return (-1); - } - } + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); return (__acl_aclcheck_link(pathp, type, &acl->ats_acl)); } @@ -121,20 +109,14 @@ acl_valid_link_np(const char *pathp, acl_type_t type, acl_t acl) int acl_valid_fd_np(int fd, acl_type_t type, acl_t acl) { - int error; if (acl == NULL) { errno = EINVAL; return (-1); } type = _acl_type_unold(type); - if (_posix1e_acl(acl, type)) { - error = _posix1e_acl_sort(acl); - if (error) { - errno = error; - return (-1); - } - } + if (_posix1e_acl(acl, type)) + _posix1e_acl_sort(acl); acl->ats_cur_entry = 0; diff --git a/lib/libc/posix1e/mac.3 b/lib/libc/posix1e/mac.3 index 6499d6b..af162f8 100644 --- a/lib/libc/posix1e/mac.3 +++ b/lib/libc/posix1e/mac.3 @@ -74,7 +74,7 @@ When querying a label on an object, a .Vt mac_t must first be prepared using the interfaces described in .Xr mac_prepare 3 , -allowing the application to declare which policies it wishes to interogate. +allowing the application to declare which policies it wishes to interrogate. The application writer can also rely on default label names declared in .Xr mac.conf 5 . .Pp @@ -109,7 +109,7 @@ This function, described in .Xr mac_set 3 , sets the MAC label associated with the current process. .It Fn mac_free -This function, desribed in +This function, described in .Xr mac_free 3 , frees working MAC label storage. .It Fn mac_from_text @@ -154,7 +154,7 @@ system objects, but without policy-specific knowledge. .Sh STANDARDS These APIs are loosely based on the APIs described in POSIX.1e, as described in IEEE POSIX.1e draft 17. -However, the resemblence of these APIs to the POSIX APIs is loose, as the +However, the resemblance of these APIs to the POSIX APIs is loose, as the POSIX APIs were unable to express some notions required for flexible and extensible access control. .Sh HISTORY diff --git a/lib/libc/posix1e/mac_prepare.3 b/lib/libc/posix1e/mac_prepare.3 index 1d85229..8e694de 100644 --- a/lib/libc/posix1e/mac_prepare.3 +++ b/lib/libc/posix1e/mac_prepare.3 @@ -31,8 +31,8 @@ .\" $FreeBSD$ .\" .Dd August 22, 2003 -.Os .Dt MAC_PREPARE 3 +.Os .Sh NAME .Nm mac_prepare , mac_prepare_type , mac_prepare_file_label , .Nm mac_prepare_ifnet_label , mac_prepare_process_label diff --git a/lib/libc/powerpc/gen/_ctx_start.S b/lib/libc/powerpc/gen/_ctx_start.S index a269e86..2d3cfcf 100644 --- a/lib/libc/powerpc/gen/_ctx_start.S +++ b/lib/libc/powerpc/gen/_ctx_start.S @@ -41,3 +41,5 @@ * above branch. */ bl PIC_PLT(CNAME(abort)) /* abort */ + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/gen/_setjmp.S b/lib/libc/powerpc/gen/_setjmp.S index 6d6e5e0..9b9f86e 100644 --- a/lib/libc/powerpc/gen/_setjmp.S +++ b/lib/libc/powerpc/gen/_setjmp.S @@ -69,3 +69,5 @@ ENTRY(_longjmp) bnelr li %r3,1 blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/gen/fabs.S b/lib/libc/powerpc/gen/fabs.S index 79475ca..7891012 100644 --- a/lib/libc/powerpc/gen/fabs.S +++ b/lib/libc/powerpc/gen/fabs.S @@ -33,3 +33,5 @@ __FBSDID("$FreeBSD$"); ENTRY(fabs) fabs %f1,%f1 blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/gen/modf.c b/lib/libc/powerpc/gen/modf.c index 37786dc..612c506 100644 --- a/lib/libc/powerpc/gen/modf.c +++ b/lib/libc/powerpc/gen/modf.c @@ -86,7 +86,7 @@ modf(val, iptr) * 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 the fractional part is the part with the rest of the + * 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 diff --git a/lib/libc/powerpc/gen/setjmp.S b/lib/libc/powerpc/gen/setjmp.S index a796120..6aaf81c 100644 --- a/lib/libc/powerpc/gen/setjmp.S +++ b/lib/libc/powerpc/gen/setjmp.S @@ -89,3 +89,4 @@ ENTRY(__longjmp) li %r3,1 blr + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/gen/sigsetjmp.S b/lib/libc/powerpc/gen/sigsetjmp.S index 3d5d1e5..5a6fd21 100644 --- a/lib/libc/powerpc/gen/sigsetjmp.S +++ b/lib/libc/powerpc/gen/sigsetjmp.S @@ -95,3 +95,5 @@ ENTRY(siglongjmp) bnelr li %r3,1 blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/sys/brk.S b/lib/libc/powerpc/sys/brk.S index 9223db3..018eec9 100644 --- a/lib/libc/powerpc/sys/brk.S +++ b/lib/libc/powerpc/sys/brk.S @@ -71,3 +71,5 @@ ENTRY(brk) 1: b PIC_PLT(HIDENAME(cerror)) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/sys/cerror.S b/lib/libc/powerpc/sys/cerror.S index 91a3006..7667cb8 100644 --- a/lib/libc/powerpc/sys/cerror.S +++ b/lib/libc/powerpc/sys/cerror.S @@ -54,4 +54,4 @@ HIDENAME(cerror): li %r4,-1 blr /* return to callers caller */ - + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/sys/exect.S b/lib/libc/powerpc/sys/exect.S index d5f9c20..3c39b3c 100644 --- a/lib/libc/powerpc/sys/exect.S +++ b/lib/libc/powerpc/sys/exect.S @@ -37,3 +37,5 @@ ENTRY(exect) blr 1: b PIC_PLT(HIDENAME(cerror)) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/sys/pipe.S b/lib/libc/powerpc/sys/pipe.S index 3ca2358..3f6d9a4 100644 --- a/lib/libc/powerpc/sys/pipe.S +++ b/lib/libc/powerpc/sys/pipe.S @@ -41,3 +41,5 @@ ENTRY(pipe) blr /* and return 0 */ 1: b PIC_PLT(HIDENAME(cerror)) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/sys/ptrace.S b/lib/libc/powerpc/sys/ptrace.S index f47fc67..0bc25c9 100644 --- a/lib/libc/powerpc/sys/ptrace.S +++ b/lib/libc/powerpc/sys/ptrace.S @@ -56,3 +56,5 @@ ENTRY(ptrace) blr 1: b PIC_PLT(HIDENAME(cerror)) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/sys/sbrk.S b/lib/libc/powerpc/sys/sbrk.S index 47fc0fe..a5e4020 100644 --- a/lib/libc/powerpc/sys/sbrk.S +++ b/lib/libc/powerpc/sys/sbrk.S @@ -68,3 +68,5 @@ ENTRY(sbrk) blr 2: b PIC_PLT(HIDENAME(cerror)) + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc/sys/setlogin.S b/lib/libc/powerpc/sys/setlogin.S index c65e639..e0d6d3c 100644 --- a/lib/libc/powerpc/sys/setlogin.S +++ b/lib/libc/powerpc/sys/setlogin.S @@ -47,3 +47,5 @@ SYSCALL(setlogin) stw %r5,CNAME(_logname_valid)@l(%r4) #endif blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/Makefile.inc b/lib/libc/powerpc64/Makefile.inc new file mode 100644 index 0000000..e4ccbb9 --- /dev/null +++ b/lib/libc/powerpc64/Makefile.inc @@ -0,0 +1,5 @@ +# $FreeBSD$ + +# Long double is 64-bits +MDSRCS+=machdep_ldisd.c +SYM_MAPS+=${.CURDIR}/powerpc64/Symbol.map diff --git a/lib/libc/powerpc64/SYS.h b/lib/libc/powerpc64/SYS.h new file mode 100644 index 0000000..a361767 --- /dev/null +++ b/lib/libc/powerpc64/SYS.h @@ -0,0 +1,99 @@ +/*- + * Copyright (c) 2002 Benno Rice. All rights reserved. + * Copyright (c) 2002 David E. O'Brien. All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * 3. Neither the name of the author nor the names of any 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 REGENTS OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: SYS.h,v 1.8 2002/01/14 00:55:56 thorpej Exp $ + * $FreeBSD$ + */ + +#include <sys/syscall.h> +#include <machine/asm.h> + +#define _SYSCALL(x) \ + .text; \ + .align 2; \ + li 0,(__CONCAT(SYS_,x)); \ + sc + +#define SYSCALL(x) \ + .text; \ + .align 2; \ +2: mflr %r0; \ + std %r0,16(%r1); \ + stdu %r1,-48(%r1); \ + bl CNAME(HIDENAME(cerror)); \ + nop; \ + addi %r1,%r1,48; \ + ld %r0,16(%r1); \ + mtlr %r0; \ + blr; \ +ENTRY(__CONCAT(__sys_,x)); \ + .weak CNAME(x); \ + .set CNAME(x),CNAME(__CONCAT(__sys_,x)); \ + .weak CNAME(__CONCAT(_,x)); \ + .set CNAME(__CONCAT(_,x)),CNAME(__CONCAT(__sys_,x)); \ + _SYSCALL(x); \ + bso 2b + +#define PSEUDO(x) \ + .text; \ + .align 2; \ +ENTRY(__CONCAT(__sys_,x)); \ + .weak CNAME(__CONCAT(_,x)); \ + .set CNAME(__CONCAT(_,x)),CNAME(__CONCAT(__sys_,x)); \ + _SYSCALL(x); \ + bnslr; \ + mflr %r0; \ + std %r0,16(%r1); \ + stdu %r1,-48(%r1); \ + bl CNAME(HIDENAME(cerror)); \ + nop; \ + addi %r1,%r1,48; \ + ld %r0,16(%r1); \ + mtlr %r0; \ + blr; + +#define RSYSCALL(x) \ + .text; \ + .align 2; \ +ENTRY(__CONCAT(__sys_,x)); \ + .weak CNAME(x); \ + .set CNAME(x),CNAME(__CONCAT(__sys_,x)); \ + .weak CNAME(__CONCAT(_,x)); \ + .set CNAME(__CONCAT(_,x)),CNAME(__CONCAT(__sys_,x)); \ + _SYSCALL(x); \ + bnslr; \ + \ + mflr %r0; \ + std %r0,16(%r1); \ + stdu %r1,-48(%r1); \ + bl CNAME(HIDENAME(cerror)); \ + nop; \ + addi %r1,%r1,48; \ + ld %r0,16(%r1); \ + mtlr %r0; \ + blr; diff --git a/lib/libc/powerpc64/Symbol.map b/lib/libc/powerpc64/Symbol.map new file mode 100644 index 0000000..0314d0d --- /dev/null +++ b/lib/libc/powerpc64/Symbol.map @@ -0,0 +1,59 @@ +/* + * $FreeBSD$ + */ + +/* + * This only needs to contain symbols that are not listed in + * symbol maps from other parts of libc (i.e., not found in + * stdlib/Symbol.map, string/Symbol.map, sys/Symbol.map, ...). + */ +FBSD_1.0 { + /* PSEUDO syscalls */ + _exit; + + _mcount; + _setjmp; + _longjmp; + fabs; + __flt_rounds; + fpgetmask; + fpgetround; + fpgetsticky; + fpsetmask; + fpsetround; + __infinity; + __nan; + makecontext; + modf; + setjmp; + longjmp; + sigsetjmp; + siglongjmp; + htonl; + htons; + ntohl; + ntohs; + brk; + exect; + sbrk; + vfork; +}; + +FBSDprivate_1.0 { + /* PSEUDO syscalls */ + __sys_getlogin; + _getlogin; + __sys_exit; + + _set_tp; + _fpgetsticky; + __makecontext; + __longjmp; + signalcontext; + __signalcontext; + __syncicache; + _end; + _curbrk; + _minbrk; + _cerror; +}; diff --git a/lib/libc/powerpc64/_fpmath.h b/lib/libc/powerpc64/_fpmath.h new file mode 100644 index 0000000..6d80eb4 --- /dev/null +++ b/lib/libc/powerpc64/_fpmath.h @@ -0,0 +1,49 @@ +/*- + * 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$ + */ + +union IEEEl2bits { + long double e; + struct { + unsigned int sign :1; + unsigned int exp :11; + unsigned int manh :20; + unsigned int manl :32; + } bits; +}; + +#define mask_nbit_l(u) ((void)0) +#define LDBL_IMPLICIT_NBIT +#define LDBL_NBIT 0 + +#define LDBL_MANH_SIZE 20 +#define LDBL_MANL_SIZE 32 + +#define LDBL_TO_ARRAY32(u, a) do { \ + (a)[0] = (uint32_t)(u).bits.manl; \ + (a)[1] = (uint32_t)(u).bits.manh; \ +} while(0) diff --git a/lib/libc/powerpc64/arith.h b/lib/libc/powerpc64/arith.h new file mode 100644 index 0000000..8e2c9ec --- /dev/null +++ b/lib/libc/powerpc64/arith.h @@ -0,0 +1,16 @@ +/* + * MD header for contrib/gdtoa + * + * $FreeBSD$ + */ + +/* + * NOTE: The definitions in this file must be correct or strtod(3) and + * floating point formats in printf(3) will break! The file can be + * generated by running contrib/gdtoa/arithchk.c on the target + * architecture. See contrib/gdtoa/gdtoaimp.h for details. + */ + +#define IEEE_MC68k +#define Arith_Kind_ASL 2 +#define Double_Align diff --git a/lib/libc/powerpc64/gd_qnan.h b/lib/libc/powerpc64/gd_qnan.h new file mode 100644 index 0000000..d70d8c3 --- /dev/null +++ b/lib/libc/powerpc64/gd_qnan.h @@ -0,0 +1,21 @@ +/* + * MD header for contrib/gdtoa + * + * This file can be generated by compiling and running contrib/gdtoa/qnan.c + * on the target architecture after arith.h has been generated. + * + * $FreeBSD$ + */ + +#define f_QNAN 0x7fc00000 +#define d_QNAN0 0x7ff80000 +#define d_QNAN1 0x0 +#define ld_QNAN0 0x7ff80000 +#define ld_QNAN1 0x0 +#define ld_QNAN2 0x0 +#define ld_QNAN3 0x0 +#define ldus_QNAN0 0x7ff8 +#define ldus_QNAN1 0x0 +#define ldus_QNAN2 0x0 +#define ldus_QNAN3 0x0 +#define ldus_QNAN4 0x0 diff --git a/lib/libc/powerpc64/gen/Makefile.inc b/lib/libc/powerpc64/gen/Makefile.inc new file mode 100644 index 0000000..4b381c3 --- /dev/null +++ b/lib/libc/powerpc64/gen/Makefile.inc @@ -0,0 +1,9 @@ +# $FreeBSD$ + +SRCS += _ctx_start.S fabs.S flt_rounds.c fpgetmask.c fpgetround.c \ + fpgetsticky.c fpsetmask.c fpsetround.c \ + infinity.c ldexp.c makecontext.c modf.c _setjmp.S \ + setjmp.S sigsetjmp.S signalcontext.c syncicache.c \ + _set_tp.c + + diff --git a/lib/libc/powerpc64/gen/_ctx_start.S b/lib/libc/powerpc64/gen/_ctx_start.S new file mode 100644 index 0000000..79df041 --- /dev/null +++ b/lib/libc/powerpc64/gen/_ctx_start.S @@ -0,0 +1,50 @@ +/* + * Copyright (c) 2004 Suleiman Souhlal + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING 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$"); + + .globl CNAME(_ctx_done) + .globl CNAME(abort) + + ENTRY(_ctx_start) + ld %r2,8(%r14) + ld %r14,0(%r14) + mtlr %r14 + blrl /* branch to start function */ + mr %r3,%r15 /* pass pointer to ucontext as argument */ + nop + bl CNAME(_ctx_done) /* branch to ctxt completion func */ + /* + * we should never return from the + * above branch. + */ + nop + bl CNAME(abort) /* abort */ + nop + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/gen/_set_tp.c b/lib/libc/powerpc64/gen/_set_tp.c new file mode 100644 index 0000000..9adb6a5 --- /dev/null +++ b/lib/libc/powerpc64/gen/_set_tp.c @@ -0,0 +1,35 @@ +/*- + * Copyright (c) 2004 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. + * + * $FreeBSD$ + */ + +void +_set_tp(void *tpval) +{ + register void *tp __asm__("r13"); + + __asm __volatile("mr %0,%1" : "=r"(tp) : "r"((char*)tpval + 0x7010)); +} diff --git a/lib/libc/powerpc64/gen/_setjmp.S b/lib/libc/powerpc64/gen/_setjmp.S new file mode 100644 index 0000000..a5c247d --- /dev/null +++ b/lib/libc/powerpc64/gen/_setjmp.S @@ -0,0 +1,118 @@ +/*- + * Copyright (c) 2002 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: _setjmp.S,v 1.1 1997/03/29 20:55:53 thorpej Exp $ */ + +#include <machine/asm.h> +__FBSDID("$FreeBSD$"); + +/* + * 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. + * + * jmpbuf layout: + * +------------+ + * | unused | + * +------------+ + * | unused | + * | | + * | (4 words) | + * | | + * +------------+ + * | saved regs | + * | ... | + */ + +ENTRY(_setjmp) + mflr %r11 + mfcr %r12 + mr %r10,%r1 + mr %r9,%r2 + std %r9,40 + 0*8(%r3) + std %r10,40 + 1*8(%r3) + std %r11,40 + 2*8(%r3) + std %r12,40 + 3*8(%r3) + std %r13,40 + 4*8(%r3) + std %r14,40 + 5*8(%r3) + std %r15,40 + 6*8(%r3) + std %r16,40 + 7*8(%r3) + std %r17,40 + 8*8(%r3) + std %r18,40 + 9*8(%r3) + std %r19,40 + 10*8(%r3) + std %r20,40 + 11*8(%r3) + std %r21,40 + 12*8(%r3) + std %r22,40 + 13*8(%r3) + std %r23,40 + 14*8(%r3) + std %r24,40 + 15*8(%r3) + std %r25,40 + 16*8(%r3) + std %r26,40 + 17*8(%r3) + std %r27,40 + 18*8(%r3) + std %r28,40 + 19*8(%r3) + std %r29,40 + 20*8(%r3) + std %r30,40 + 21*8(%r3) + std %r31,40 + 22*8(%r3) + li %r3,0 + blr + +ENTRY(_longjmp) + ld %r9,40 + 0*8(%r3) + ld %r10,40 + 1*8(%r3) + ld %r11,40 + 2*8(%r3) + ld %r12,40 + 3*8(%r3) + ld %r13,40 + 4*8(%r3) + ld %r14,40 + 5*8(%r3) + ld %r15,40 + 6*8(%r3) + ld %r16,40 + 7*8(%r3) + ld %r17,40 + 8*8(%r3) + ld %r18,40 + 9*8(%r3) + ld %r19,40 + 10*8(%r3) + ld %r20,40 + 11*8(%r3) + ld %r21,40 + 12*8(%r3) + ld %r22,40 + 13*8(%r3) + ld %r23,40 + 14*8(%r3) + ld %r24,40 + 15*8(%r3) + ld %r25,40 + 16*8(%r3) + ld %r26,40 + 17*8(%r3) + ld %r27,40 + 18*8(%r3) + ld %r28,40 + 19*8(%r3) + ld %r29,40 + 20*8(%r3) + ld %r30,40 + 21*8(%r3) + ld %r31,40 + 22*8(%r3) + + mtlr %r11 + mtcr %r12 + mr %r2,%r9 + mr %r1,%r10 + or. %r3,%r4,%r4 + bnelr + li %r3,1 + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/gen/fabs.S b/lib/libc/powerpc64/gen/fabs.S new file mode 100644 index 0000000..7891012 --- /dev/null +++ b/lib/libc/powerpc64/gen/fabs.S @@ -0,0 +1,37 @@ +/* + * Copyright (c) 2004 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING 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$"); + +/* + * double fabs(double) + */ +ENTRY(fabs) + fabs %f1,%f1 + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/i386/string/strlen.S b/lib/libc/powerpc64/gen/flt_rounds.c index 6e91f1a..6294be7 100644 --- a/lib/libc/i386/string/strlen.S +++ b/lib/libc/powerpc64/gen/flt_rounds.c @@ -1,5 +1,7 @@ +/* $NetBSD: flt_rounds.c,v 1.4.10.3 2002/03/22 20:41:53 nathanw Exp $ */ + /* - * Copyright (c) 1993 Winning Strategies, Inc. + * Copyright (c) 1996 Mark Brinicombe * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -12,7 +14,8 @@ * 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 Winning Strategies, Inc. + * 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 * @@ -28,27 +31,26 @@ * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ -#include <machine/asm.h> +#include <sys/cdefs.h> __FBSDID("$FreeBSD$"); -/* - * strlen (s) - * compute the length of the string s. - * - * Written by: - * J.T. Conklin (jtc@wimsey.com), Winning Strategies, Inc. - */ +#include <sys/types.h> +#include <machine/float.h> + +#ifndef _SOFT_FLOAT +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() +{ + uint64_t fpscr; -ENTRY(strlen) - pushl %edi - movl 8(%esp),%edi /* string address */ - cld /* set search forward */ - xorl %eax,%eax /* set search for null terminator */ - movl $-1,%ecx /* set search for lots of characters */ - repne /* search! */ - scasb - notl %ecx /* get length by taking complement */ - leal -1(%ecx),%eax /* and subtracting one */ - popl %edi - ret -END(strlen) + __asm__ __volatile("mffs %0" : "=f"(fpscr)); + return map[(fpscr & 0x03)]; +} +#endif diff --git a/lib/libc/powerpc64/gen/fpgetmask.c b/lib/libc/powerpc64/gen/fpgetmask.c new file mode 100644 index 0000000..aa7623b --- /dev/null +++ b/lib/libc/powerpc64/gen/fpgetmask.c @@ -0,0 +1,55 @@ +/* $NetBSD: fpgetmask.c,v 1.3 2002/01/13 21:45:47 thorpej 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. + * 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> +__FBSDID("$FreeBSD$"); + +#include <sys/types.h> +#include <ieeefp.h> + +#ifndef _SOFT_FLOAT +fp_except_t +fpgetmask() +{ + u_int64_t fpscr; + + __asm__("mffs %0" : "=f"(fpscr)); + return ((fp_except_t)((fpscr >> 3) & 0x1f)); +} +#endif diff --git a/lib/libc/powerpc64/gen/fpgetround.c b/lib/libc/powerpc64/gen/fpgetround.c new file mode 100644 index 0000000..5381378 --- /dev/null +++ b/lib/libc/powerpc64/gen/fpgetround.c @@ -0,0 +1,55 @@ +/* $NetBSD: fpgetround.c,v 1.3 2002/01/13 21:45:47 thorpej 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. + * 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> +__FBSDID("$FreeBSD$"); + +#include <sys/types.h> +#include <ieeefp.h> + +#ifndef _SOFT_FLOAT +fp_rnd_t +fpgetround() +{ + u_int64_t fpscr; + + __asm__("mffs %0" : "=f"(fpscr)); + return ((fp_rnd_t)(fpscr & 0x3)); +} +#endif diff --git a/lib/libc/powerpc64/gen/fpgetsticky.c b/lib/libc/powerpc64/gen/fpgetsticky.c new file mode 100644 index 0000000..feb2ccc --- /dev/null +++ b/lib/libc/powerpc64/gen/fpgetsticky.c @@ -0,0 +1,61 @@ +/* $NetBSD: fpgetsticky.c,v 1.3 2002/01/13 21:45:48 thorpej 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. + * 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. + * + * $FreeBSD$ + */ + +#include <sys/cdefs.h> + +#include "namespace.h" + +#include <sys/types.h> +#include <ieeefp.h> + +#ifndef _SOFT_FLOAT +#ifdef __weak_alias +__weak_alias(fpgetsticky,_fpgetsticky) +#endif + +fp_except_t +fpgetsticky() +{ + u_int64_t fpscr; + + __asm__ __volatile("mffs %0" : "=f"(fpscr)); + return ((fp_except_t)((fpscr >> 25) & 0x1f)); +} +#endif diff --git a/lib/libc/powerpc64/gen/fpsetmask.c b/lib/libc/powerpc64/gen/fpsetmask.c new file mode 100644 index 0000000..e1433a5 --- /dev/null +++ b/lib/libc/powerpc64/gen/fpsetmask.c @@ -0,0 +1,59 @@ +/* $NetBSD: fpsetmask.c,v 1.3 2002/01/13 21:45:48 thorpej 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. + * 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> +__FBSDID("$FreeBSD$"); + +#include <sys/types.h> +#include <ieeefp.h> + +#ifndef _SOFT_FLOAT +fp_except_t +fpsetmask(fp_except_t mask) +{ + u_int64_t fpscr; + fp_rnd_t old; + + __asm__("mffs %0" : "=f"(fpscr)); + old = (fp_rnd_t)((fpscr >> 3) & 0x1f); + fpscr = (fpscr & 0xffffff07) | (mask << 3); + __asm__ __volatile("mtfsf 0xff,%0" :: "f"(fpscr)); + return (old); +} +#endif diff --git a/lib/libc/powerpc64/gen/fpsetround.c b/lib/libc/powerpc64/gen/fpsetround.c new file mode 100644 index 0000000..b4f00d4 --- /dev/null +++ b/lib/libc/powerpc64/gen/fpsetround.c @@ -0,0 +1,59 @@ +/* $NetBSD: fpsetround.c,v 1.3 2002/01/13 21:45:48 thorpej 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. + * 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> +__FBSDID("$FreeBSD$"); + +#include <sys/types.h> +#include <ieeefp.h> + +#ifndef _SOFT_FLOAT +fp_rnd_t +fpsetround(fp_rnd_t rnd_dir) +{ + u_int64_t fpscr; + fp_rnd_t old; + + __asm__ __volatile("mffs %0" : "=f"(fpscr)); + old = (fp_rnd_t)(fpscr & 0x3); + fpscr = (fpscr & 0xfffffffc) | rnd_dir; + __asm__ __volatile("mtfsf 0xff,%0" :: "f"(fpscr)); + return (old); +} +#endif diff --git a/lib/libc/powerpc64/gen/infinity.c b/lib/libc/powerpc64/gen/infinity.c new file mode 100644 index 0000000..cf1695e --- /dev/null +++ b/lib/libc/powerpc64/gen/infinity.c @@ -0,0 +1,17 @@ +#include <sys/cdefs.h> +#if 0 +#if defined(LIBC_SCCS) && !defined(lint) +__RCSID("$NetBSD: infinity.c,v 1.2 1998/11/14 19:31:02 christos Exp $"); +#endif /* LIBC_SCCS and not lint */ +#endif +__FBSDID("$FreeBSD$"); + +/* infinity.c */ + +#include <math.h> + +/* bytes for +Infinity on powerpc */ +const union __infinity_un __infinity = { { 0x7f, 0xf0, 0, 0, 0, 0, 0, 0 } }; + +/* bytes for NaN */ +const union __nan_un __nan = { { 0xff, 0xc0, 0, 0 } }; diff --git a/lib/libc/powerpc64/gen/makecontext.c b/lib/libc/powerpc64/gen/makecontext.c new file mode 100644 index 0000000..6d980f3 --- /dev/null +++ b/lib/libc/powerpc64/gen/makecontext.c @@ -0,0 +1,118 @@ +/* + * Copyright (c) 2004 Suleiman Souhlal + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) 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$"); + +#include <sys/param.h> + +#include <stdarg.h> +#include <stdlib.h> +#include <unistd.h> +#include <stdio.h> +#include <ucontext.h> + +__weak_reference(__makecontext, makecontext); + +void _ctx_done(ucontext_t *ucp); +void _ctx_start(void); + +void +_ctx_done(ucontext_t *ucp) +{ + if (ucp->uc_link == NULL) + exit(0); + else { + /* invalidate context */ + ucp->uc_mcontext.mc_len = 0; + + setcontext((const ucontext_t *)ucp->uc_link); + + abort(); /* should never return from above call */ + } +} + +void +__makecontext(ucontext_t *ucp, void (*start)(void), int argc, ...) +{ + mcontext_t *mc; + char *sp; + va_list ap; + int i, regargs, stackargs; + + /* Sanity checks */ + if ((ucp == NULL) || (argc < 0) || (argc > NCARGS) + || (ucp->uc_stack.ss_sp == NULL) + || (ucp->uc_stack.ss_size < MINSIGSTKSZ)) { + /* invalidate context */ + ucp->uc_mcontext.mc_len = 0; + return; + } + + /* + * The stack must have space for the frame pointer, saved + * link register, overflow arguments, and be 16-byte + * aligned. + */ + stackargs = (argc > 8) ? argc - 8 : 0; + sp = (char *) ucp->uc_stack.ss_sp + ucp->uc_stack.ss_size + - sizeof(uintptr_t)*(stackargs + 2); + sp = (char *)((uintptr_t)sp & ~0x1f); + + mc = &ucp->uc_mcontext; + + /* + * Up to 8 register args. Assumes all args are 64-bit and + * integer only. Not sure how to cater for floating point. + */ + regargs = (argc > 8) ? 8 : argc; + va_start(ap, argc); + for (i = 0; i < regargs; i++) + mc->mc_gpr[3 + i] = va_arg(ap, uint64_t); + + /* + * Overflow args go onto the stack + */ + if (argc > 8) { + uint64_t *argp; + + /* Skip past frame pointer and saved LR */ + argp = (uint64_t *)sp + 6; + + for (i = 0; i < stackargs; i++) + *argp++ = va_arg(ap, uint64_t); + } + va_end(ap); + + /* + * Use caller-saved regs 14/15 to hold params that _ctx_start + * will use to invoke the user-supplied func + */ + mc->mc_srr0 = (uintptr_t) _ctx_start; + mc->mc_gpr[1] = (uintptr_t) sp; /* new stack pointer */ + mc->mc_gpr[14] = (uintptr_t) start; /* r14 <- start */ + mc->mc_gpr[15] = (uintptr_t) ucp; /* r15 <- ucp */ +} diff --git a/lib/libc/powerpc64/gen/modf.c b/lib/libc/powerpc64/gen/modf.c new file mode 100644 index 0000000..612c506 --- /dev/null +++ b/lib/libc/powerpc64/gen/modf.c @@ -0,0 +1,107 @@ +/* + * 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. + * + * $NetBSD: modf.c,v 1.1 1995/02/10 17:50:25 cgd Exp $ + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +#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(val, iptr) + double val, *iptr; +{ + union doub { + double v; + struct ieee_double s; + } u, v; + u_int64_t frac; + + /* + * If input is Inf or NaN, return it and leave i alone. + */ + u.v = val; + if (u.s.dbl_exp == DBL_EXP_INFNAN) + return (u.v); + + /* + * If input can't have a fractional part, return + * (appropriately signed) zero, and make i be the input. + */ + if ((int)u.s.dbl_exp - DBL_EXP_BIAS > DBL_FRACBITS - 1) { + *iptr = u.v; + v.v = 0.0; + v.s.dbl_sign = u.s.dbl_sign; + return (v.v); + } + + /* + * If |input| < 1.0, return it, and set i to the appropriately + * signed zero. + */ + if (u.s.dbl_exp < DBL_EXP_BIAS) { + v.v = 0.0; + v.s.dbl_sign = u.s.dbl_sign; + *iptr = v.v; + return (u.v); + } + + /* + * 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.v = u.v; + /* Zero the low bits of the fraction, the sleazy way. */ + frac = ((u_int64_t)v.s.dbl_frach << 32) + v.s.dbl_fracl; + frac >>= DBL_FRACBITS - (u.s.dbl_exp - DBL_EXP_BIAS); + frac <<= DBL_FRACBITS - (u.s.dbl_exp - DBL_EXP_BIAS); + v.s.dbl_fracl = frac & 0xffffffff; + v.s.dbl_frach = frac >> 32; + *iptr = v.v; + + u.v -= v.v; + u.s.dbl_sign = v.s.dbl_sign; + return (u.v); +} diff --git a/lib/libc/powerpc64/gen/setjmp.S b/lib/libc/powerpc64/gen/setjmp.S new file mode 100644 index 0000000..0f33ab2 --- /dev/null +++ b/lib/libc/powerpc64/gen/setjmp.S @@ -0,0 +1,140 @@ +/*- + * Copyright (c) 2002 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: setjmp.S,v 1.3 1998/10/03 12:30:38 tsubai Exp $ */ + +#include <machine/asm.h> +__FBSDID("$FreeBSD$"); + +#include <sys/syscall.h> + +/* + * 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. + * + * jmpbuf layout: + * +------------+ + * | unused | + * +------------+ + * | sig state | + * | | + * | (4 words) | + * | | + * +------------+ + * | saved regs | + * | ... | + */ + +ENTRY(setjmp) + mr %r6,%r3 + li %r3,1 /* SIG_BLOCK, but doesn't matter */ + /* since set == NULL */ + li %r4,0 /* set = NULL */ + mr %r5,%r6 /* &oset */ + addi %r5,%r5,4 + li %r0, SYS_sigprocmask /*sigprocmask(SIG_BLOCK, NULL, &oset)*/ + sc /*assume no error XXX */ + mflr %r11 /* r11 <- link reg */ + mfcr %r12 /* r12 <- condition reg */ + mr %r10,%r1 /* r10 <- stackptr */ + mr %r9,%r2 /* r9 <- global ptr */ + + std %r9,40 + 0*8(%r6) + std %r10,40 + 1*8(%r6) + std %r11,40 + 2*8(%r6) + std %r12,40 + 3*8(%r6) + std %r13,40 + 4*8(%r6) + std %r14,40 + 5*8(%r6) + std %r15,40 + 6*8(%r6) + std %r16,40 + 7*8(%r6) + std %r17,40 + 8*8(%r6) + std %r18,40 + 9*8(%r6) + std %r19,40 + 10*8(%r6) + std %r20,40 + 11*8(%r6) + std %r21,40 + 12*8(%r6) + std %r22,40 + 13*8(%r6) + std %r23,40 + 14*8(%r6) + std %r24,40 + 15*8(%r6) + std %r25,40 + 16*8(%r6) + std %r26,40 + 17*8(%r6) + std %r27,40 + 18*8(%r6) + std %r28,40 + 19*8(%r6) + std %r29,40 + 20*8(%r6) + std %r30,40 + 21*8(%r6) + std %r31,40 + 22*8(%r6) + + li %r3,0 /* return (0) */ + blr + + .weak CNAME(longjmp) + .set CNAME(longjmp),CNAME(__longjmp) + .weak CNAME(.longjmp) + .set CNAME(.longjmp),CNAME(.__longjmp) +ENTRY(__longjmp) + ld %r9,40 + 0*8(%r3) + ld %r10,40 + 1*8(%r3) + ld %r11,40 + 2*8(%r3) + ld %r12,40 + 3*8(%r3) + ld %r13,40 + 4*8(%r3) + ld %r14,40 + 5*8(%r3) + ld %r15,40 + 6*8(%r3) + ld %r16,40 + 7*8(%r3) + ld %r17,40 + 8*8(%r3) + ld %r18,40 + 9*8(%r3) + ld %r19,40 + 10*8(%r3) + ld %r20,40 + 11*8(%r3) + ld %r21,40 + 12*8(%r3) + ld %r22,40 + 13*8(%r3) + ld %r23,40 + 14*8(%r3) + ld %r24,40 + 15*8(%r3) + ld %r25,40 + 16*8(%r3) + ld %r26,40 + 17*8(%r3) + ld %r27,40 + 18*8(%r3) + ld %r28,40 + 19*8(%r3) + ld %r29,40 + 20*8(%r3) + ld %r30,40 + 21*8(%r3) + ld %r31,40 + 22*8(%r3) + mr %r6,%r4 /* save val param */ + mtlr %r11 /* r11 -> link reg */ + mtcr %r12 /* r12 -> condition reg */ + mr %r2,%r9 /* r9 -> global ptr */ + mr %r1,%r10 /* r10 -> stackptr */ + mr %r4,%r3 + li %r3,3 /* SIG_SETMASK */ + addi %r4,%r4,4 /* &set */ + li %r5,0 /* oset = NULL */ + li %r0,SYS_sigprocmask /* sigprocmask(SIG_SET, &set, NULL) */ + sc /* assume no error XXX */ + or. %r3,%r6,%r6 + bnelr + li %r3,1 + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/gen/signalcontext.c b/lib/libc/powerpc64/gen/signalcontext.c new file mode 100644 index 0000000..fad9ee1 --- /dev/null +++ b/lib/libc/powerpc64/gen/signalcontext.c @@ -0,0 +1,103 @@ +/* + * Copyright (c) 2004 Marcel Moolenaar, Peter Grehan + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list 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> +__FBSDID("$FreeBSD$"); + +#include <sys/param.h> +#include <sys/ucontext.h> +#include <signal.h> +#include <stdlib.h> +#include <strings.h> + +typedef void (*handler_t)(uint32_t, uint32_t, uint32_t); + +/* Prototypes */ +static void ctx_wrapper(ucontext_t *ucp, handler_t func, uint32_t sig, + uint32_t sig_si, uint32_t sig_uc); + +__weak_reference(__signalcontext, signalcontext); + +int +__signalcontext(ucontext_t *ucp, int sig, __sighandler_t *func) +{ + siginfo_t *sig_si; + ucontext_t *sig_uc; + uintptr_t sp; + + /* Bail out if we don't have a valid ucontext pointer. */ + if (ucp == NULL) + abort(); + + /* + * Build a 16-byte-aligned signal frame + */ + sp = (ucp->uc_mcontext.mc_gpr[1] - sizeof(ucontext_t)) & ~15UL; + sig_uc = (ucontext_t *)sp; + bcopy(ucp, sig_uc, sizeof(*sig_uc)); + sp = (sp - sizeof(siginfo_t)) & ~15UL; + sig_si = (siginfo_t *)sp; + bzero(sig_si, sizeof(*sig_si)); + sig_si->si_signo = sig; + + /* + * Subtract 48 bytes from stack to allow for frameptr + */ + sp -= 6*sizeof(uint64_t); + sp &= ~15UL; + + /* + * Setup the ucontext of the signal handler. + */ + bzero(&ucp->uc_mcontext, sizeof(ucp->uc_mcontext)); + ucp->uc_link = sig_uc; + sigdelset(&ucp->uc_sigmask, sig); + + ucp->uc_mcontext.mc_vers = _MC_VERSION; + ucp->uc_mcontext.mc_len = sizeof(struct __mcontext); + ucp->uc_mcontext.mc_srr0 = (uint64_t) ctx_wrapper; + ucp->uc_mcontext.mc_gpr[1] = (uint64_t) sp; + ucp->uc_mcontext.mc_gpr[3] = (uint64_t) func; + ucp->uc_mcontext.mc_gpr[4] = (uint64_t) sig; + ucp->uc_mcontext.mc_gpr[5] = (uint64_t) sig_si; + ucp->uc_mcontext.mc_gpr[6] = (uint64_t) sig_uc; + + return (0); +} + +static void +ctx_wrapper(ucontext_t *ucp, handler_t func, uint32_t sig, uint32_t sig_si, + uint32_t sig_uc) +{ + + (*func)(sig, sig_si, sig_uc); + if (ucp->uc_link == NULL) + exit(0); + setcontext((const ucontext_t *)ucp->uc_link); + /* should never get here */ + abort(); + /* NOTREACHED */ +} diff --git a/lib/libc/powerpc64/gen/sigsetjmp.S b/lib/libc/powerpc64/gen/sigsetjmp.S new file mode 100644 index 0000000..7b50f9f --- /dev/null +++ b/lib/libc/powerpc64/gen/sigsetjmp.S @@ -0,0 +1,146 @@ +/*- + * Copyright (c) 2002 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: sigsetjmp.S,v 1.4 1998/10/03 12:30:38 tsubai Exp $ */ + +#include <machine/asm.h> +__FBSDID("$FreeBSD$"); + +/* + * C library -- sigsetjmp, siglongjmp + * + * siglongjmp(a,v) + * will generate a "return(v?v:1)" from the last call to + * sigsetjmp(a, savemask) + * by restoring registers from the stack. + * The previous signal state is restored if savemask is non-zero + * + * jmpbuf layout: + * +------------+ + * | savemask | + * +------------+ + * | sig state | + * | | + * | (4 words) | + * | | + * +------------+ + * | saved regs | + * | ... | + */ + + +#include <sys/syscall.h> + +ENTRY(sigsetjmp) + mr %r6,%r3 + stw %r4,0(%r3) + or. %r7,%r4,%r4 + beq 1f + li %r3,1 /* SIG_BLOCK, but doesn't matter */ + /* since set == NULL */ + li %r4,0 /* set = NULL */ + mr %r5,%r6 /* &oset */ + addi %r5,%r5,4 + li %r0, SYS_sigprocmask /* sigprocmask(SIG_BLOCK, NULL, &oset)*/ + sc /* assume no error XXX */ +1: + mflr %r11 + mfcr %r12 + mr %r10,%r1 + mr %r9,%r2 + + std %r9,40 + 0*8(%r6) + std %r10,40 + 1*8(%r6) + std %r11,40 + 2*8(%r6) + std %r12,40 + 3*8(%r6) + std %r13,40 + 4*8(%r6) + std %r14,40 + 5*8(%r6) + std %r15,40 + 6*8(%r6) + std %r16,40 + 7*8(%r6) + std %r17,40 + 8*8(%r6) + std %r18,40 + 9*8(%r6) + std %r19,40 + 10*8(%r6) + std %r20,40 + 11*8(%r6) + std %r21,40 + 12*8(%r6) + std %r22,40 + 13*8(%r6) + std %r23,40 + 14*8(%r6) + std %r24,40 + 15*8(%r6) + std %r25,40 + 16*8(%r6) + std %r26,40 + 17*8(%r6) + std %r27,40 + 18*8(%r6) + std %r28,40 + 19*8(%r6) + std %r29,40 + 20*8(%r6) + std %r30,40 + 21*8(%r6) + std %r31,40 + 22*8(%r6) + + li %r3,0 + blr + +ENTRY(siglongjmp) + ld %r9,40 + 0*8(%r3) + ld %r10,40 + 1*8(%r3) + ld %r11,40 + 2*8(%r3) + ld %r12,40 + 3*8(%r3) + ld %r13,40 + 4*8(%r3) + ld %r14,40 + 5*8(%r3) + ld %r15,40 + 6*8(%r3) + ld %r16,40 + 7*8(%r3) + ld %r17,40 + 8*8(%r3) + ld %r18,40 + 9*8(%r3) + ld %r19,40 + 10*8(%r3) + ld %r20,40 + 11*8(%r3) + ld %r21,40 + 12*8(%r3) + ld %r22,40 + 13*8(%r3) + ld %r23,40 + 14*8(%r3) + ld %r24,40 + 15*8(%r3) + ld %r25,40 + 16*8(%r3) + ld %r26,40 + 17*8(%r3) + ld %r27,40 + 18*8(%r3) + ld %r28,40 + 19*8(%r3) + ld %r29,40 + 20*8(%r3) + ld %r30,40 + 21*8(%r3) + ld %r31,40 + 22*8(%r3) + + lwz %r7,0(%r3) + mr %r6,%r4 + mtlr %r11 + mtcr %r12 + mr %r2,%r9 + mr %r1,%r10 + or. %r7,%r7,%r7 + beq 1f + mr %r4,%r3 + li %r3,3 /* SIG_SETMASK */ + addi %r4,%r4,4 /* &set */ + li %r5,0 /* oset = NULL */ + li %r0,SYS_sigprocmask /* sigprocmask(SIG_SET, &set, NULL) */ + sc /* assume no error XXX */ +1: + or. %r3,%r6,%r6 + bnelr + li %r3,1 + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/gen/syncicache.c b/lib/libc/powerpc64/gen/syncicache.c new file mode 100644 index 0000000..1267c9f --- /dev/null +++ b/lib/libc/powerpc64/gen/syncicache.c @@ -0,0 +1,103 @@ +/*- + * 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. + * + * $NetBSD: syncicache.c,v 1.2 1999/05/05 12:36:40 tsubai Exp $ + */ + +#ifndef lint +static const char rcsid[] = + "$FreeBSD$"; +#endif /* not lint */ + +#include <sys/param.h> +#if defined(_KERNEL) || defined(_STANDALONE) +#include <sys/time.h> +#include <sys/proc.h> +#include <vm/vm.h> +#endif +#include <sys/sysctl.h> + +#include <machine/cpu.h> +#include <machine/md_var.h> + +#ifdef _STANDALONE +int cacheline_size = 32; +#endif + +#if !defined(_KERNEL) && !defined(_STANDALONE) +#include <stdlib.h> + +int cacheline_size = 0; + +static void getcachelinesize(void); + +static void +getcachelinesize() +{ + static int cachemib[] = { CTL_MACHDEP, CPU_CACHELINE }; + long clen; + + clen = sizeof(cacheline_size); + + if (sysctl(cachemib, sizeof(cachemib) / sizeof(cachemib[0]), + &cacheline_size, &clen, NULL, 0) < 0 || !cacheline_size) { + abort(); + } +} +#endif + +void +__syncicache(void *from, int len) +{ + off_t l, off; + char *p; + +#if !defined(_KERNEL) && !defined(_STANDALONE) + if (!cacheline_size) + getcachelinesize(); +#endif + + off = (uintptr_t)from & (cacheline_size - 1); + l = len += off; + p = (char *)from - off; + + do { + __asm __volatile ("dcbst 0,%0" :: "r"(p)); + p += cacheline_size; + } while ((l -= cacheline_size) > 0); + __asm __volatile ("sync"); + p = (char *)from - off; + do { + __asm __volatile ("icbi 0,%0" :: "r"(p)); + p += cacheline_size; + } while ((len -= cacheline_size) > 0); + __asm __volatile ("sync; isync"); +} + diff --git a/lib/libc/powerpc64/softfloat/milieu.h b/lib/libc/powerpc64/softfloat/milieu.h new file mode 100644 index 0000000..e2e43b1 --- /dev/null +++ b/lib/libc/powerpc64/softfloat/milieu.h @@ -0,0 +1,49 @@ +/* $NetBSD: milieu.h,v 1.1 2000/12/29 20:13:54 bjh21 Exp $ */ +/* $FreeBSD$ */ + +/* +=============================================================================== + +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/libc/powerpc64/softfloat/powerpc-gcc.h b/lib/libc/powerpc64/softfloat/powerpc-gcc.h new file mode 100644 index 0000000..e2f8680 --- /dev/null +++ b/lib/libc/powerpc64/softfloat/powerpc-gcc.h @@ -0,0 +1,92 @@ +/* $NetBSD: arm-gcc.h,v 1.2 2001/02/21 18:09:25 bjh21 Exp $ */ +/* $FreeBSD$ */ + +/* +------------------------------------------------------------------------------- +One of the macros `BIGENDIAN' or `LITTLEENDIAN' must be defined. +------------------------------------------------------------------------------- +*/ +#define BIGENDIAN + +/* +------------------------------------------------------------------------------- +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 int uint8; +typedef int int8; +typedef unsigned 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/libc/powerpc64/softfloat/softfloat.h b/lib/libc/powerpc64/softfloat/softfloat.h new file mode 100644 index 0000000..6b9c9b0 --- /dev/null +++ b/lib/libc/powerpc64/softfloat/softfloat.h @@ -0,0 +1,307 @@ +/* $NetBSD: softfloat.h,v 1.6 2002/05/12 13:12:46 bjh21 Exp $ */ +/* $FreeBSD$ */ + +/* 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_t 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. +------------------------------------------------------------------------------- +*/ +typedef fp_except_t fp_except; + +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 ); +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 ); +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 ); +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/libc/powerpc64/sys/Makefile.inc b/lib/libc/powerpc64/sys/Makefile.inc new file mode 100644 index 0000000..5193cc2 --- /dev/null +++ b/lib/libc/powerpc64/sys/Makefile.inc @@ -0,0 +1,11 @@ +# $FreeBSD$ + +MDASM+= brk.S cerror.S exect.S pipe.S ptrace.S sbrk.S setlogin.S + +# Don't generate default code for these syscalls: +NOASM= break.o exit.o getlogin.o openbsd_poll.o sstk.o yield.o + +PSEUDO= _getlogin.o _exit.o +.if !defined(WITHOUT_SYSCALL_COMPAT) +PSEUDO+= _pread.o _pwrite.o _lseek.o _mmap.o _ftruncate.o _truncate.o +.endif diff --git a/lib/libc/powerpc64/sys/brk.S b/lib/libc/powerpc64/sys/brk.S new file mode 100644 index 0000000..675b400 --- /dev/null +++ b/lib/libc/powerpc64/sys/brk.S @@ -0,0 +1,73 @@ +/*- + * Copyright (c) 2002 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: brk.S,v 1.9 2000/06/26 06:25:43 kleink Exp $ */ + +#include <machine/asm.h> +__FBSDID("$FreeBSD$"); + +#include "SYS.h" + + .globl HIDENAME(curbrk) + .globl HIDENAME(minbrk) + .globl CNAME(_end) + + .data + .align 3 +HIDENAME(minbrk): + .llong CNAME(_end) + + .text + +ENTRY(brk) + addis %r6,%r2,HIDENAME(minbrk)@toc@ha + ld %r6,HIDENAME(minbrk)@toc@l(%r6) + cmpld %r6,%r3 /* if (minbrk <= r3) */ + bgt 0f + mr %r6,%r3 /* r6 = r3 */ +0: + mr %r3,%r6 /* new break value */ + li %r0,SYS_break + sc /* assume, that r5 is kept */ + bso 1f + + /* record new break */ + addis %r7,%r2,HIDENAME(curbrk)@toc@ha + std %r6,HIDENAME(curbrk)@toc@l(%r7) + + blr /* return 0 */ + +1: + mflr %r0 + std %r0,16(%r1) + stdu %r1,-48(%r1) + bl HIDENAME(cerror) + nop + ld %r1,0(%r1) + ld %r0,16(%r1) + mtlr %r0 + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/sys/cerror.S b/lib/libc/powerpc64/sys/cerror.S new file mode 100644 index 0000000..9bf33bf --- /dev/null +++ b/lib/libc/powerpc64/sys/cerror.S @@ -0,0 +1,60 @@ +/*- + * Copyright (c) 2002 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: cerror.S,v 1.5 2000/01/27 14:58:48 kleink Exp $ */ + +#include <machine/asm.h> +__FBSDID("$FreeBSD$"); + +#include "SYS.h" + + .globl HIDENAME(cerror) + .globl CNAME(__error) + + /* + * The __error() function is thread aware. For non-threaded + * programs and the initial threaded in threaded programs, + * it returns a pointer to the global errno variable. + */ +ENTRY(HIDENAME(cerror)) + mflr %r0 + std %r0,16(%r1) /* save lr */ + stdu %r1,-64(%r1) /* allocate new stack frame */ + std %r31,48(%r1) + + mr %r31,%r3 /* stash errval in callee-saved register */ + bl CNAME(__error) + nop + stw %r31,0(%r3) /* store errval into &errno */ + + ld %r31,48(%r1) + ld %r1,0(%r1) + ld %r0,16(%r1) + mtlr %r0 + li %r3,-1 + li %r4,-1 + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/sys/exect.S b/lib/libc/powerpc64/sys/exect.S new file mode 100644 index 0000000..aa34b9e --- /dev/null +++ b/lib/libc/powerpc64/sys/exect.S @@ -0,0 +1,49 @@ +/*- + * Copyright (c) 2002 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: exect.S,v 1.3 1998/05/25 15:28:03 ws Exp $ */ + +#include <machine/asm.h> +__FBSDID("$FreeBSD$"); + +#include "SYS.h" + +ENTRY(exect) + li %r0,SYS_execve + sc + bso 1f + blr +1: + mflr %r0 + std %r0,16(%r1) + stdu %r1,-48(%r1) + bl HIDENAME(cerror) + nop + ld %r1,0(%r1) + ld %r0,16(%r1) + mtlr %r0 + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/sys/pipe.S b/lib/libc/powerpc64/sys/pipe.S new file mode 100644 index 0000000..efd3dd6 --- /dev/null +++ b/lib/libc/powerpc64/sys/pipe.S @@ -0,0 +1,53 @@ +/*- + * Copyright (c) 2002 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: pipe.S,v 1.6 2000/09/28 08:38:54 kleink Exp $ */ + +#include <machine/asm.h> +__FBSDID("$FreeBSD$"); + +#include "SYS.h" + +ENTRY(pipe) + mr %r5,%r3 /* save pointer */ + li %r0,SYS_pipe + sc /* r5 is preserved */ + bso 1f + stw %r3,0(%r5) /* success, store fds */ + stw %r4,4(%r5) + li %r3,0 + blr /* and return 0 */ +1: + mflr %r0 + std %r0,16(%r1) + stdu %r1,-48(%r1) + bl HIDENAME(cerror) + nop + ld %r1,0(%r1) + ld %r0,16(%r1) + mtlr %r0 + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/sys/ptrace.S b/lib/libc/powerpc64/sys/ptrace.S new file mode 100644 index 0000000..ede00e7 --- /dev/null +++ b/lib/libc/powerpc64/sys/ptrace.S @@ -0,0 +1,67 @@ +/*- + * Copyright (c) 2002 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: ptrace.S,v 1.3 2000/02/23 20:16:57 kleink Exp $ */ + +#include <machine/asm.h> +__FBSDID("$FreeBSD$"); + +#include "SYS.h" + +ENTRY(ptrace) + mflr %r0 + std %r0,16(%r1) + stdu %r1,-80(%r1) + stw %r3,48(%r1) + stw %r4,52(%r1) + std %r5,56(%r1) + stw %r6,64(%r1) + + bl CNAME(__error) + nop + li %r7,0 + stw %r7,0(%r3) + + lwz %r3,48(%r1) + lwz %r4,52(%r1) + ld %r5,56(%r1) + lwz %r6,64(%r1) + ld %r1,0(%r1) + ld %r0,16(%r1) + mtlr %r0 + li %r0,SYS_ptrace + sc + bso 1f + blr +1: + stdu %r1,-48(%r1) /* lr already saved */ + bl HIDENAME(cerror) + nop + ld %r1,0(%r1) + ld %r0,16(%r1) + mtlr %r0 + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/sys/sbrk.S b/lib/libc/powerpc64/sys/sbrk.S new file mode 100644 index 0000000..e147493 --- /dev/null +++ b/lib/libc/powerpc64/sys/sbrk.S @@ -0,0 +1,68 @@ +/*- + * Copyright (c) 2002 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: sbrk.S,v 1.8 2000/06/26 06:25:44 kleink Exp $ */ + +#include <machine/asm.h> +__FBSDID("$FreeBSD$"); + +#include "SYS.h" + + .globl HIDENAME(curbrk) + .globl CNAME(_end) + + .data + .align 3 +HIDENAME(curbrk): + .llong CNAME(_end) + + .text +ENTRY(sbrk) + addis %r5,%r2,HIDENAME(curbrk)@toc@ha + addi %r5,%r5,HIDENAME(curbrk)@toc@l + ld %r6,0(%r5) /* r6 = old break */ + cmpdi %r3,0 /* sbrk(0) - return curbrk */ + beq 1f + add %r3,%r3,%r6 + mr %r7,%r3 /* r7 = new break */ + li %r0,SYS_break + sc /* break(new_break) */ + bso 2f + std %r7,0(%r5) +1: + mr %r3,%r6 /* set return value */ + blr +2: + mflr %r0 + std %r0,16(%r1) + stdu %r1,-48(%r1) + bl HIDENAME(cerror) + nop + ld %r1,0(%r1) + ld %r0,16(%r1) + mtlr %r0 + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/powerpc64/sys/setlogin.S b/lib/libc/powerpc64/sys/setlogin.S new file mode 100644 index 0000000..6183407 --- /dev/null +++ b/lib/libc/powerpc64/sys/setlogin.S @@ -0,0 +1,41 @@ +/*- + * Copyright (c) 2002 Peter Grehan. + * All rights reserved. + * + * Redistribution and use in source and binary forms, with or without + * modification, are permitted provided that the following conditions + * are met: + * 1. Redistributions of source code must retain the above copyright + * notice, this list of conditions and the following disclaimer. + * 2. Redistributions in binary form must reproduce the above copyright + * notice, this list of conditions and the following disclaimer in the + * documentation and/or other materials provided with the distribution. + * + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND + * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE + * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE + * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL + * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS + * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) + * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT + * LIABILITY, OR TORT (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: setlogin.S,v 1.3 1998/11/24 11:14:57 tsubai Exp $ */ + +#include <machine/asm.h> +__FBSDID("$FreeBSD$"); + +#include "SYS.h" + + .globl CNAME(_logname_valid) /* in _getlogin() */ + +SYSCALL(setlogin) + addis %r4,%r2,CNAME(_logname_valid)@toc@ha + li %r5,0 + stw %r5,CNAME(_logname_valid)@toc@l(%r4) + blr + + .section .note.GNU-stack,"",%progbits diff --git a/lib/libc/quad/Makefile.inc b/lib/libc/quad/Makefile.inc index 14a5b1f..016fa34 100644 --- a/lib/libc/quad/Makefile.inc +++ b/lib/libc/quad/Makefile.inc @@ -2,9 +2,9 @@ # $FreeBSD$ # Quad support, if needed -.PATH: ${.CURDIR}/${MACHINE_ARCH}/quad ${.CURDIR}/quad +.PATH: ${.CURDIR}/${LIBC_ARCH}/quad ${.CURDIR}/quad -.if ${MACHINE_ARCH} == "i386" +.if ${LIBC_ARCH} == "i386" SRCS+= cmpdi2.c divdi3.c moddi3.c qdivrem.c ucmpdi2.c udivdi3.c umoddi3.c diff --git a/lib/libc/regex/re_format.7 b/lib/libc/regex/re_format.7 index 463c6a2..a2a527d 100644 --- a/lib/libc/regex/re_format.7 +++ b/lib/libc/regex/re_format.7 @@ -275,7 +275,6 @@ and stands for the list of all characters belonging to that class. Standard character class names are: -.Pp .Bl -column "alnum" "digit" "xdigit" -offset indent .It Em "alnum digit punct" .It Em "alpha graph space" diff --git a/lib/libc/rpc/PSD.doc/nfs.rfc.ms b/lib/libc/rpc/PSD.doc/nfs.rfc.ms deleted file mode 100644 index 13d7619..0000000 --- a/lib/libc/rpc/PSD.doc/nfs.rfc.ms +++ /dev/null @@ -1,1374 +0,0 @@ -.\" -.\" Must use -- tbl -- with this one -.\" -.\" @(#)nfs.rfc.ms 2.2 88/08/05 4.0 RPCSRC -.\" $FreeBSD$ -.\" -.de BT -.if \\n%=1 .tl ''- % -'' -.. -.ND -.\" prevent excess underlining in nroff -.if n .fp 2 R -.OH 'Network File System: Version 2 Protocol Specification''Page %' -.EH 'Page %''Network File System: Version 2 Protocol Specification' -.if \n%=1 .bp -.SH -\&Network File System: Version 2 Protocol Specification -.IX NFS "" "" "" PAGE MAJOR -.IX "Network File System" "" "" "" PAGE MAJOR -.IX NFS "version-2 protocol specification" -.IX "Network File System" "version-2 protocol specification" -.LP -.NH 0 -\&Status of this Standard -.LP -Note: This document specifies a protocol that Sun Microsystems, Inc., -and others are using. It specifies it in standard ARPA RFC form. -.NH 1 -\&Introduction -.IX NFS introduction -.LP -The Sun Network Filesystem (NFS) protocol provides transparent remote -access to shared filesystems over local area networks. The NFS -protocol is designed to be machine, operating system, network architecture, -and transport protocol independent. This independence is -achieved through the use of Remote Procedure Call (RPC) primitives -built on top of an External Data Representation (XDR). Implementations -exist for a variety of machines, from personal computers to -supercomputers. -.LP -The supporting mount protocol allows the server to hand out remote -access privileges to a restricted set of clients. It performs the -operating system-specific functions that allow, for example, to -attach remote directory trees to some local file system. -.NH 2 -\&Remote Procedure Call -.IX "Remote Procedure Call" -.LP -Sun's remote procedure call specification provides a procedure- -oriented interface to remote services. Each server supplies a -program that is a set of procedures. NFS is one such "program". -The combination of host address, program number, and procedure -number specifies one remote service procedure. RPC does not depend -on services provided by specific protocols, so it can be used with -any underlying transport protocol. See the -.I "Remote Procedure Calls: Protocol Specification" -chapter of this manual. -.NH 2 -\&External Data Representation -.IX "External Data Representation" -.LP -The External Data Representation (XDR) standard provides a common -way of representing a set of data types over a network. -The NFS -Protocol Specification is written using the RPC data description -language. -For more information, see the -.I " External Data Representation Standard: Protocol Specification." -Sun provides implementations of XDR and -RPC, but NFS does not require their use. Any software that -provides equivalent functionality can be used, and if the encoding -is exactly the same it can interoperate with other implementations -of NFS. -.NH 2 -\&Stateless Servers -.IX "stateless servers" -.IX servers stateless -.LP -The NFS protocol is stateless. That is, a server does not need to -maintain any extra state information about any of its clients in -order to function correctly. Stateless servers have a distinct -advantage over stateful servers in the event of a failure. With -stateless servers, a client need only retry a request until the -server responds; it does not even need to know that the server has -crashed, or the network temporarily went down. The client of a -stateful server, on the other hand, needs to either detect a server -crash and rebuild the server's state when it comes back up, or -cause client operations to fail. -.LP -This may not sound like an important issue, but it affects the -protocol in some unexpected ways. We feel that it is worth a bit -of extra complexity in the protocol to be able to write very simple -servers that do not require fancy crash recovery. -.LP -On the other hand, NFS deals with objects such as files and -directories that inherently have state -- what good would a file be -if it did not keep its contents intact? The goal is to not -introduce any extra state in the protocol itself. Another way to -simplify recovery is by making operations "idempotent" whenever -possible (so that they can potentially be repeated). -.NH 1 -\&NFS Protocol Definition -.IX NFS "protocol definition" -.IX NFS protocol -.LP -Servers have been known to change over time, and so can the -protocol that they use. So RPC provides a version number with each -RPC request. This RFC describes version two of the NFS protocol. -Even in the second version, there are various obsolete procedures -and parameters, which will be removed in later versions. An RFC -for version three of the NFS protocol is currently under -preparation. -.NH 2 -\&File System Model -.IX filesystem model -.LP -NFS assumes a file system that is hierarchical, with directories as -all but the bottom-level files. Each entry in a directory (file, -directory, device, etc.) has a string name. Different operating -systems may have restrictions on the depth of the tree or the names -used, as well as using different syntax to represent the "pathname", -which is the concatenation of all the "components" (directory and -file names) in the name. A "file system" is a tree on a single -server (usually a single disk or physical partition) with a specified -"root". Some operating systems provide a "mount" operation to make -all file systems appear as a single tree, while others maintain a -"forest" of file systems. Files are unstructured streams of -uninterpreted bytes. Version 3 of NFS uses a slightly more general -file system model. -.LP -NFS looks up one component of a pathname at a time. It may not be -obvious why it does not just take the whole pathname, traipse down -the directories, and return a file handle when it is done. There are -several good reasons not to do this. First, pathnames need -separators between the directory components, and different operating -systems use different separators. We could define a Network Standard -Pathname Representation, but then every pathname would have to be -parsed and converted at each end. Other issues are discussed in -\fINFS Implementation Issues\fP below. -.LP -Although files and directories are similar objects in many ways, -different procedures are used to read directories and files. This -provides a network standard format for representing directories. The -same argument as above could have been used to justify a procedure -that returns only one directory entry per call. The problem is -efficiency. Directories can contain many entries, and a remote call -to return each would be just too slow. -.NH 2 -\&RPC Information -.IX NFS "RPC information" -.IP \fIAuthentication\fP -The NFS service uses -.I AUTH_UNIX , -.I AUTH_DES , -or -.I AUTH_SHORT -style -authentication, except in the NULL procedure where -.I AUTH_NONE -is also allowed. -.IP "\fITransport Protocols\fP" -NFS currently is supported on UDP/IP only. -.IP "\fIPort Number\fP" -The NFS protocol currently uses the UDP port number 2049. This is -not an officially assigned port, so later versions of the protocol -use the \*QPortmapping\*U facility of RPC. -.NH 2 -\&Sizes of XDR Structures -.IX "XDR structure sizes" -.LP -These are the sizes, given in decimal bytes, of various XDR -structures used in the protocol: -.DS -/* \fIThe maximum number of bytes of data in a READ or WRITE request\fP */ -const MAXDATA = 8192; - -/* \fIThe maximum number of bytes in a pathname argument\fP */ -const MAXPATHLEN = 1024; - -/* \fIThe maximum number of bytes in a file name argument\fP */ -const MAXNAMLEN = 255; - -/* \fIThe size in bytes of the opaque "cookie" passed by READDIR\fP */ -const COOKIESIZE = 4; - -/* \fIThe size in bytes of the opaque file handle\fP */ -const FHSIZE = 32; -.DE -.NH 2 -\&Basic Data Types -.IX "NFS data types" -.IX NFS "basic data types" -.LP -The following XDR definitions are basic structures and types used -in other structures described further on. -.KS -.NH 3 -\&stat -.IX "NFS data types" stat "" \fIstat\fP -.DS -enum stat { - NFS_OK = 0, - NFSERR_PERM=1, - NFSERR_NOENT=2, - NFSERR_IO=5, - NFSERR_NXIO=6, - NFSERR_ACCES=13, - NFSERR_EXIST=17, - NFSERR_NODEV=19, - NFSERR_NOTDIR=20, - NFSERR_ISDIR=21, - NFSERR_FBIG=27, - NFSERR_NOSPC=28, - NFSERR_ROFS=30, - NFSERR_NAMETOOLONG=63, - NFSERR_NOTEMPTY=66, - NFSERR_DQUOT=69, - NFSERR_STALE=70, - NFSERR_WFLUSH=99 -}; -.DE -.KE -.LP -The -.I stat -type is returned with every procedure's results. A -value of -.I NFS_OK -indicates that the call completed successfully and -the results are valid. The other values indicate some kind of -error occurred on the server side during the servicing of the -procedure. The error values are derived from UNIX error numbers. -.IP \fBNFSERR_PERM\fP: -Not owner. The caller does not have correct ownership -to perform the requested operation. -.IP \fBNFSERR_NOENT\fP: -No such file or directory. The file or directory -specified does not exist. -.IP \fBNFSERR_IO\fP: -Some sort of hard error occurred when the operation was -in progress. This could be a disk error, for example. -.IP \fBNFSERR_NXIO\fP: -No such device or address. -.IP \fBNFSERR_ACCES\fP: -Permission denied. The caller does not have the -correct permission to perform the requested operation. -.IP \fBNFSERR_EXIST\fP: -File exists. The file specified already exists. -.IP \fBNFSERR_NODEV\fP: -No such device. -.IP \fBNFSERR_NOTDIR\fP: -Not a directory. The caller specified a -non-directory in a directory operation. -.IP \fBNFSERR_ISDIR\fP: -Is a directory. The caller specified a directory in -a non- directory operation. -.IP \fBNFSERR_FBIG\fP: -File too large. The operation caused a file to grow -beyond the server's limit. -.IP \fBNFSERR_NOSPC\fP: -No space left on device. The operation caused the -server's filesystem to reach its limit. -.IP \fBNFSERR_ROFS\fP: -Read-only filesystem. Write attempted on a read-only filesystem. -.IP \fBNFSERR_NAMETOOLONG\fP: -File name too long. The file name in an operation was too long. -.IP \fBNFSERR_NOTEMPTY\fP: -Directory not empty. Attempted to remove a -directory that was not empty. -.IP \fBNFSERR_DQUOT\fP: -Disk quota exceeded. The client's disk quota on the -server has been exceeded. -.IP \fBNFSERR_STALE\fP: -The "fhandle" given in the arguments was invalid. -That is, the file referred to by that file handle no longer exists, -or access to it has been revoked. -.IP \fBNFSERR_WFLUSH\fP: -The server's write cache used in the -.I WRITECACHE -call got flushed to disk. -.LP -.KS -.NH 3 -\&ftype -.IX "NFS data types" ftype "" \fIftype\fP -.DS -enum ftype { - NFNON = 0, - NFREG = 1, - NFDIR = 2, - NFBLK = 3, - NFCHR = 4, - NFLNK = 5 -}; -.DE -.KE -The enumeration -.I ftype -gives the type of a file. The type -.I NFNON -indicates a non-file, -.I NFREG -is a regular file, -.I NFDIR -is a directory, -.I NFBLK -is a block-special device, -.I NFCHR -is a character-special device, and -.I NFLNK -is a symbolic link. -.KS -.NH 3 -\&fhandle -.IX "NFS data types" fhandle "" \fIfhandle\fP -.DS -typedef opaque fhandle[FHSIZE]; -.DE -.KE -The -.I fhandle -is the file handle passed between the server and the client. -All file operations are done using file handles to refer to a file or -directory. The file handle can contain whatever information the server -needs to distinguish an individual file. -.KS -.NH 3 -\&timeval -.IX "NFS data types" timeval "" \fItimeval\fP -.DS -struct timeval { - unsigned int seconds; - unsigned int useconds; -}; -.DE -.KE -The -.I timeval -structure is the number of seconds and microseconds -since midnight January 1, 1970, Greenwich Mean Time. It is used to -pass time and date information. -.KS -.NH 3 -\&fattr -.IX "NFS data types" fattr "" \fIfattr\fP -.DS -struct fattr { - ftype type; - unsigned int mode; - unsigned int nlink; - unsigned int uid; - unsigned int gid; - unsigned int size; - unsigned int blocksize; - unsigned int rdev; - unsigned int blocks; - unsigned int fsid; - unsigned int fileid; - timeval atime; - timeval mtime; - timeval ctime; -}; -.DE -.KE -The -.I fattr -structure contains the attributes of a file; "type" is the type of -the file; "nlink" is the number of hard links to the file (the number -of different names for the same file); "uid" is the user -identification number of the owner of the file; "gid" is the group -identification number of the group of the file; "size" is the size in -bytes of the file; "blocksize" is the size in bytes of a block of the -file; "rdev" is the device number of the file if it is type -.I NFCHR -or -.I NFBLK ; -"blocks" is the number of blocks the file takes up on disk; "fsid" is -the file system identifier for the filesystem containing the file; -"fileid" is a number that uniquely identifies the file within its -filesystem; "atime" is the time when the file was last accessed for -either read or write; "mtime" is the time when the file data was last -modified (written); and "ctime" is the time when the status of the -file was last changed. Writing to the file also changes "ctime" if -the size of the file changes. -.LP -"mode" is the access mode encoded as a set of bits. Notice that the -file type is specified both in the mode bits and in the file type. -This is really a bug in the protocol and will be fixed in future -versions. The descriptions given below specify the bit positions -using octal numbers. -.TS -box tab (&) ; -cfI cfI -lfL l . -Bit&Description -_ -0040000&This is a directory; "type" field should be NFDIR. -0020000&This is a character special file; "type" field should be NFCHR. -0060000&This is a block special file; "type" field should be NFBLK. -0100000&This is a regular file; "type" field should be NFREG. -0120000&This is a symbolic link file; "type" field should be NFLNK. -0140000&This is a named socket; "type" field should be NFNON. -0004000&Set user id on execution. -0002000&Set group id on execution. -0001000&Save swapped text even after use. -0000400&Read permission for owner. -0000200&Write permission for owner. -0000100&Execute and search permission for owner. -0000040&Read permission for group. -0000020&Write permission for group. -0000010&Execute and search permission for group. -0000004&Read permission for others. -0000002&Write permission for others. -0000001&Execute and search permission for others. -.TE -.KS -Notes: -.IP -The bits are the same as the mode bits returned by the -.I stat(2) -system call in the UNIX system. The file type is specified both in -the mode bits and in the file type. This is fixed in future -versions. -.IP -The "rdev" field in the attributes structure is an operating system -specific device specifier. It will be removed and generalized in -the next revision of the protocol. -.KE -.LP -.KS -.NH 3 -\&sattr -.IX "NFS data types" sattr "" \fIsattr\fP -.DS -struct sattr { - unsigned int mode; - unsigned int uid; - unsigned int gid; - unsigned int size; - timeval atime; - timeval mtime; -}; -.DE -.KE -The -.I sattr -structure contains the file attributes which can be set -from the client. The fields are the same as for -.I fattr -above. A "size" of zero means the file should be truncated. -A value of -1 indicates a field that should be ignored. -.LP -.KS -.NH 3 -\&filename -.IX "NFS data types" filename "" \fIfilename\fP -.DS -typedef string filename<MAXNAMLEN>; -.DE -.KE -The type -.I filename -is used for passing file names or pathname components. -.LP -.KS -.NH 3 -\&path -.IX "NFS data types" path "" \fIpath\fP -.DS -typedef string path<MAXPATHLEN>; -.DE -.KE -The type -.I path -is a pathname. The server considers it as a string -with no internal structure, but to the client it is the name of a -node in a filesystem tree. -.LP -.KS -.NH 3 -\&attrstat -.IX "NFS data types" attrstat "" \fIattrstat\fP -.DS -union attrstat switch (stat status) { - case NFS_OK: - fattr attributes; - default: - void; -}; -.DE -.KE -The -.I attrstat -structure is a common procedure result. It contains -a "status" and, if the call succeeded, it also contains the -attributes of the file on which the operation was done. -.LP -.KS -.NH 3 -\&diropargs -.IX "NFS data types" diropargs "" \fIdiropargs\fP -.DS -struct diropargs { - fhandle dir; - filename name; -}; -.DE -.KE -The -.I diropargs -structure is used in directory operations. The -"fhandle" "dir" is the directory in which to find the file "name". -A directory operation is one in which the directory is affected. -.LP -.KS -.NH 3 -\&diropres -.IX "NFS data types" diropres "" \fIdiropres\fP -.DS -union diropres switch (stat status) { - case NFS_OK: - struct { - fhandle file; - fattr attributes; - } diropok; - default: - void; -}; -.DE -.KE -The results of a directory operation are returned in a -.I diropres -structure. If the call succeeded, a new file handle "file" and the -"attributes" associated with that file are returned along with the -"status". -.NH 2 -\&Server Procedures -.IX "NFS server procedures" "" "" "" PAGE MAJOR -.LP -The protocol definition is given as a set of procedures with -arguments and results defined using the RPC language. A brief -description of the function of each procedure should provide enough -information to allow implementation. -.LP -All of the procedures in the NFS protocol are assumed to be -synchronous. When a procedure returns to the client, the client -can assume that the operation has completed and any data associated -with the request is now on stable storage. For example, a client -.I WRITE -request may cause the server to update data blocks, -filesystem information blocks (such as indirect blocks), and file -attribute information (size and modify times). When the -.I WRITE -returns to the client, it can assume that the write is safe, even -in case of a server crash, and it can discard the data written. -This is a very important part of the statelessness of the server. -If the server waited to flush data from remote requests, the client -would have to save those requests so that it could resend them in -case of a server crash. -.ie t .DS -.el .DS L - -.ft I -/* -* Remote file service routines -*/ -.ft CW -program NFS_PROGRAM { - version NFS_VERSION { - void NFSPROC_NULL(void) = 0; - attrstat NFSPROC_GETATTR(fhandle) = 1; - attrstat NFSPROC_SETATTR(sattrargs) = 2; - void NFSPROC_ROOT(void) = 3; - diropres NFSPROC_LOOKUP(diropargs) = 4; - readlinkres NFSPROC_READLINK(fhandle) = 5; - readres NFSPROC_READ(readargs) = 6; - void NFSPROC_WRITECACHE(void) = 7; - attrstat NFSPROC_WRITE(writeargs) = 8; - diropres NFSPROC_CREATE(createargs) = 9; - stat NFSPROC_REMOVE(diropargs) = 10; - stat NFSPROC_RENAME(renameargs) = 11; - stat NFSPROC_LINK(linkargs) = 12; - stat NFSPROC_SYMLINK(symlinkargs) = 13; - diropres NFSPROC_MKDIR(createargs) = 14; - stat NFSPROC_RMDIR(diropargs) = 15; - readdirres NFSPROC_READDIR(readdirargs) = 16; - statfsres NFSPROC_STATFS(fhandle) = 17; - } = 2; -} = 100003; -.DE -.KS -.NH 3 -\&Do Nothing -.IX "NFS server procedures" NFSPROC_NULL() "" \fINFSPROC_NULL()\fP -.DS -void -NFSPROC_NULL(void) = 0; -.DE -.KE -This procedure does no work. It is made available in all RPC -services to allow server response testing and timing. -.KS -.NH 3 -\&Get File Attributes -.IX "NFS server procedures" NFSPROC_GETATTR() "" \fINFSPROC_GETATTR()\fP -.DS -attrstat -NFSPROC_GETATTR (fhandle) = 1; -.DE -.KE -If the reply status is -.I NFS_OK , -then the reply attributes contains -the attributes for the file given by the input fhandle. -.KS -.NH 3 -\&Set File Attributes -.IX "NFS server procedures" NFSPROC_SETATTR() "" \fINFSPROC_SETATTR()\fP -.DS -struct sattrargs { - fhandle file; - sattr attributes; - }; - -attrstat -NFSPROC_SETATTR (sattrargs) = 2; -.DE -.KE -The "attributes" argument contains fields which are either -1 or -are the new value for the attributes of "file". If the reply -status is -.I NFS_OK , -then the reply attributes have the attributes of -the file after the "SETATTR" operation has completed. -.LP -Note: The use of -1 to indicate an unused field in "attributes" is -changed in the next version of the protocol. -.KS -.NH 3 -\&Get Filesystem Root -.IX "NFS server procedures" NFSPROC_ROOT "" \fINFSPROC_ROOT\fP -.DS -void -NFSPROC_ROOT(void) = 3; -.DE -.KE -Obsolete. This procedure is no longer used because finding the -root file handle of a filesystem requires moving pathnames between -client and server. To do this right we would have to define a -network standard representation of pathnames. Instead, the -function of looking up the root file handle is done by the -.I MNTPROC_MNT() -procedure. (See the -.I "Mount Protocol Definition" -later in this chapter for details). -.KS -.NH 3 -\&Look Up File Name -.IX "NFS server procedures" NFSPROC_LOOKUP() "" \fINFSPROC_LOOKUP()\fP -.DS -diropres -NFSPROC_LOOKUP(diropargs) = 4; -.DE -.KE -If the reply "status" is -.I NFS_OK , -then the reply "file" and reply -"attributes" are the file handle and attributes for the file "name" -in the directory given by "dir" in the argument. -.KS -.NH 3 -\&Read From Symbolic Link -.IX "NFS server procedures" NFSPROC_READLINK() "" \fINFSPROC_READLINK()\fP -.DS -union readlinkres switch (stat status) { - case NFS_OK: - path data; - default: - void; -}; - -readlinkres -NFSPROC_READLINK(fhandle) = 5; -.DE -.KE -If "status" has the value -.I NFS_OK , -then the reply "data" is the data in -the symbolic link given by the file referred to by the fhandle argument. -.LP -Note: since NFS always parses pathnames on the client, the -pathname in a symbolic link may mean something different (or be -meaningless) on a different client or on the server if a different -pathname syntax is used. -.KS -.NH 3 -\&Read From File -.IX "NFS server procedures" NFSPROC_READ "" \fINFSPROC_READ\fP -.DS -struct readargs { - fhandle file; - unsigned offset; - unsigned count; - unsigned totalcount; -}; - -union readres switch (stat status) { - case NFS_OK: - fattr attributes; - opaque data<NFS_MAXDATA>; - default: - void; -}; - -readres -NFSPROC_READ(readargs) = 6; -.DE -.KE -Returns up to "count" bytes of "data" from the file given by -"file", starting at "offset" bytes from the beginning of the file. -The first byte of the file is at offset zero. The file attributes -after the read takes place are returned in "attributes". -.LP -Note: The argument "totalcount" is unused, and is removed in the -next protocol revision. -.KS -.NH 3 -\&Write to Cache -.IX "NFS server procedures" NFSPROC_WRITECACHE() "" \fINFSPROC_WRITECACHE()\fP -.DS -void -NFSPROC_WRITECACHE(void) = 7; -.DE -.KE -To be used in the next protocol revision. -.KS -.NH 3 -\&Write to File -.IX "NFS server procedures" NFSPROC_WRITE() "" \fINFSPROC_WRITE()\fP -.DS -struct writeargs { - fhandle file; - unsigned beginoffset; - unsigned offset; - unsigned totalcount; - opaque data<NFS_MAXDATA>; -}; - -attrstat -NFSPROC_WRITE(writeargs) = 8; -.DE -.KE -Writes "data" beginning "offset" bytes from the beginning of -"file". The first byte of the file is at offset zero. If the -reply "status" is NFS_OK, then the reply "attributes" contains the -attributes of the file after the write has completed. The write -operation is atomic. Data from this call to -.I WRITE -will not be mixed with data from another client's calls. -.LP -Note: The arguments "beginoffset" and "totalcount" are ignored and -are removed in the next protocol revision. -.KS -.NH 3 -\&Create File -.IX "NFS server procedures" NFSPROC_CREATE() "" \fINFSPROC_CREATE()\fP -.DS -struct createargs { - diropargs where; - sattr attributes; -}; - -diropres -NFSPROC_CREATE(createargs) = 9; -.DE -.KE -The file "name" is created in the directory given by "dir". The -initial attributes of the new file are given by "attributes". A -reply "status" of NFS_OK indicates that the file was created, and -reply "file" and reply "attributes" are its file handle and -attributes. Any other reply "status" means that the operation -failed and no file was created. -.LP -Note: This routine should pass an exclusive create flag, meaning -"create the file only if it is not already there". -.KS -.NH 3 -\&Remove File -.IX "NFS server procedures" NFSPROC_REMOVE() "" \fINFSPROC_REMOVE()\fP -.DS -stat -NFSPROC_REMOVE(diropargs) = 10; -.DE -.KE -The file "name" is removed from the directory given by "dir". A -reply of NFS_OK means the directory entry was removed. -.LP -Note: possibly non-idempotent operation. -.KS -.NH 3 -\&Rename File -.IX "NFS server procedures" NFSPROC_RENAME() "" \fINFSPROC_RENAME()\fP -.DS -struct renameargs { - diropargs from; - diropargs to; -}; - -stat -NFSPROC_RENAME(renameargs) = 11; -.DE -.KE -The existing file "from.name" in the directory given by "from.dir" -is renamed to "to.name" in the directory given by "to.dir". If the -reply is -.I NFS_OK , -the file was renamed. The -RENAME -operation is -atomic on the server; it cannot be interrupted in the middle. -.LP -Note: possibly non-idempotent operation. -.KS -.NH 3 -\&Create Link to File -.IX "NFS server procedures" NFSPROC_LINK() "" \fINFSPROC_LINK()\fP -.DS -struct linkargs { - fhandle from; - diropargs to; -}; - -stat -NFSPROC_LINK(linkargs) = 12; -.DE -.KE -Creates the file "to.name" in the directory given by "to.dir", -which is a hard link to the existing file given by "from". If the -return value is -.I NFS_OK , -a link was created. Any other return value -indicates an error, and the link was not created. -.LP -A hard link should have the property that changes to either of the -linked files are reflected in both files. When a hard link is made -to a file, the attributes for the file should have a value for -"nlink" that is one greater than the value before the link. -.LP -Note: possibly non-idempotent operation. -.KS -.NH 3 -\&Create Symbolic Link -.IX "NFS server procedures" NFSPROC_SYMLINK() "" \fINFSPROC_SYMLINK()\fP -.DS -struct symlinkargs { - diropargs from; - path to; - sattr attributes; -}; - -stat -NFSPROC_SYMLINK(symlinkargs) = 13; -.DE -.KE -Creates the file "from.name" with ftype -.I NFLNK -in the directory -given by "from.dir". The new file contains the pathname "to" and -has initial attributes given by "attributes". If the return value -is -.I NFS_OK , -a link was created. Any other return value indicates an -error, and the link was not created. -.LP -A symbolic link is a pointer to another file. The name given in -"to" is not interpreted by the server, only stored in the newly -created file. When the client references a file that is a symbolic -link, the contents of the symbolic link are normally transparently -reinterpreted as a pathname to substitute. A -.I READLINK -operation returns the data to the client for interpretation. -.LP -Note: On UNIX servers the attributes are never used, since -symbolic links always have mode 0777. -.KS -.NH 3 -\&Create Directory -.IX "NFS server procedures" NFSPROC_MKDIR() "" \fINFSPROC_MKDIR()\fP -.DS -diropres -NFSPROC_MKDIR (createargs) = 14; -.DE -.KE -The new directory "where.name" is created in the directory given by -"where.dir". The initial attributes of the new directory are given -by "attributes". A reply "status" of NFS_OK indicates that the new -directory was created, and reply "file" and reply "attributes" are -its file handle and attributes. Any other reply "status" means -that the operation failed and no directory was created. -.LP -Note: possibly non-idempotent operation. -.KS -.NH 3 -\&Remove Directory -.IX "NFS server procedures" NFSPROC_RMDIR() "" \fINFSPROC_RMDIR()\fP -.DS -stat -NFSPROC_RMDIR(diropargs) = 15; -.DE -.KE -The existing empty directory "name" in the directory given by "dir" -is removed. If the reply is -.I NFS_OK , -the directory was removed. -.LP -Note: possibly non-idempotent operation. -.KS -.NH 3 -\&Read From Directory -.IX "NFS server procedures" NFSPROC_READDIR() "" \fINFSPROC_READDIR()\fP -.DS -struct readdirargs { - fhandle dir; - nfscookie cookie; - unsigned count; -}; - -struct entry { - unsigned fileid; - filename name; - nfscookie cookie; - entry *nextentry; -}; - -union readdirres switch (stat status) { - case NFS_OK: - struct { - entry *entries; - bool eof; - } readdirok; - default: - void; -}; - -readdirres -NFSPROC_READDIR (readdirargs) = 16; -.DE -.KE -Returns a variable number of directory entries, with a total size -of up to "count" bytes, from the directory given by "dir". If the -returned value of "status" is -.I NFS_OK , -then it is followed by a -variable number of "entry"s. Each "entry" contains a "fileid" -which consists of a unique number to identify the file within a -filesystem, the "name" of the file, and a "cookie" which is an -opaque pointer to the next entry in the directory. The cookie is -used in the next -.I READDIR -call to get more entries starting at a -given point in the directory. The special cookie zero (all bits -zero) can be used to get the entries starting at the beginning of -the directory. The "fileid" field should be the same number as the -"fileid" in the the attributes of the file. (See the -.I "Basic Data Types" -section.) -The "eof" flag has a value of -.I TRUE -if there are no more entries in the directory. -.KS -.NH 3 -\&Get Filesystem Attributes -.IX "NFS server procedures" NFSPROC_STATFS() "" \fINFSPROC_STATFS()\fP -.DS -union statfsres (stat status) { - case NFS_OK: - struct { - unsigned tsize; - unsigned bsize; - unsigned blocks; - unsigned bfree; - unsigned bavail; - } info; - default: - void; -}; - -statfsres -NFSPROC_STATFS(fhandle) = 17; -.DE -.KE -If the reply "status" is -.I NFS_OK , -then the reply "info" gives the -attributes for the filesystem that contains file referred to by the -input fhandle. The attribute fields contain the following values: -.IP tsize: -The optimum transfer size of the server in bytes. This is -the number of bytes the server would like to have in the -data part of READ and WRITE requests. -.IP bsize: -The block size in bytes of the filesystem. -.IP blocks: -The total number of "bsize" blocks on the filesystem. -.IP bfree: -The number of free "bsize" blocks on the filesystem. -.IP bavail: -The number of "bsize" blocks available to non-privileged users. -.LP -Note: This call does not work well if a filesystem has variable -size blocks. -.NH 1 -\&NFS Implementation Issues -.IX NFS implementation -.LP -The NFS protocol is designed to be operating system independent, but -since this version was designed in a UNIX environment, many -operations have semantics similar to the operations of the UNIX file -system. This section discusses some of the implementation-specific -semantic issues. -.NH 2 -\&Server/Client Relationship -.IX NFS "server/client relationship" -.LP -The NFS protocol is designed to allow servers to be as simple and -general as possible. Sometimes the simplicity of the server can be a -problem, if the client wants to implement complicated filesystem -semantics. -.LP -For example, some operating systems allow removal of open files. A -process can open a file and, while it is open, remove it from the -directory. The file can be read and written as long as the process -keeps it open, even though the file has no name in the filesystem. -It is impossible for a stateless server to implement these semantics. -The client can do some tricks such as renaming the file on remove, -and only removing it on close. We believe that the server provides -enough functionality to implement most file system semantics on the -client. -.LP -Every NFS client can also potentially be a server, and remote and -local mounted filesystems can be freely intermixed. This leads to -some interesting problems when a client travels down the directory -tree of a remote filesystem and reaches the mount point on the server -for another remote filesystem. Allowing the server to follow the -second remote mount would require loop detection, server lookup, and -user revalidation. Instead, we decided not to let clients cross a -server's mount point. When a client does a LOOKUP on a directory on -which the server has mounted a filesystem, the client sees the -underlying directory instead of the mounted directory. A client can -do remote mounts that match the server's mount points to maintain the -server's view. -.LP -.NH 2 -\&Pathname Interpretation -.IX NFS "pathname interpretation" -.LP -There are a few complications to the rule that pathnames are always -parsed on the client. For example, symbolic links could have -different interpretations on different clients. Another common -problem for non-UNIX implementations is the special interpretation of -the pathname ".." to mean the parent of a given directory. The next -revision of the protocol uses an explicit flag to indicate the parent -instead. -.NH 2 -\&Permission Issues -.IX NFS "permission issues" -.LP -The NFS protocol, strictly speaking, does not define the permission -checking used by servers. However, it is expected that a server -will do normal operating system permission checking using -.I AUTH_UNIX -style authentication as the basis of its protection mechanism. The -server gets the client's effective "uid", effective "gid", and groups -on each call and uses them to check permission. There are various -problems with this method that can been resolved in interesting ways. -.LP -Using "uid" and "gid" implies that the client and server share the -same "uid" list. Every server and client pair must have the same -mapping from user to "uid" and from group to "gid". Since every -client can also be a server, this tends to imply that the whole -network shares the same "uid/gid" space. -.I AUTH_DES -(and the next -revision of the NFS protocol) uses string names instead of numbers, -but there are still complex problems to be solved. -.LP -Another problem arises due to the usually stateful open operation. -Most operating systems check permission at open time, and then check -that the file is open on each read and write request. With stateless -servers, the server has no idea that the file is open and must do -permission checking on each read and write call. On a local -filesystem, a user can open a file and then change the permissions so -that no one is allowed to touch it, but will still be able to write -to the file because it is open. On a remote filesystem, by contrast, -the write would fail. To get around this problem, the server's -permission checking algorithm should allow the owner of a file to -access it regardless of the permission setting. -.LP -A similar problem has to do with paging in from a file over the -network. The operating system usually checks for execute permission -before opening a file for demand paging, and then reads blocks from -the open file. The file may not have read permission, but after it -is opened it doesn't matter. An NFS server can not tell the -difference between a normal file read and a demand page-in read. To -make this work, the server allows reading of files if the "uid" given -in the call has execute or read permission on the file. -.LP -In most operating systems, a particular user (on the user ID zero) -has access to all files no matter what permission and ownership they -have. This "super-user" permission may not be allowed on the server, -since anyone who can become super-user on their workstation could -gain access to all remote files. The UNIX server by default maps -user id 0 to -2 before doing its access checking. This works except -for NFS root filesystems, where super-user access cannot be avoided. -.NH 2 -\&Setting RPC Parameters -.IX NFS "setting RPC parameters" -.LP -Various file system parameters and options should be set at mount -time. The mount protocol is described in the appendix below. For -example, "Soft" mounts as well as "Hard" mounts are usually both -provided. Soft mounted file systems return errors when RPC -operations fail (after a given number of optional retransmissions), -while hard mounted file systems continue to retransmit forever. -Clients and servers may need to keep caches of recent operations to -help avoid problems with non-idempotent operations. -.NH 1 -\&Mount Protocol Definition -.IX "mount protocol" "" "" "" PAGE MAJOR -.sp 1 -.NH 2 -\&Introduction -.IX "mount protocol" introduction -.LP -The mount protocol is separate from, but related to, the NFS -protocol. It provides operating system specific services to get the -NFS off the ground -- looking up server path names, validating user -identity, and checking access permissions. Clients use the mount -protocol to get the first file handle, which allows them entry into a -remote filesystem. -.LP -The mount protocol is kept separate from the NFS protocol to make it -easy to plug in new access checking and validation methods without -changing the NFS server protocol. -.LP -Notice that the protocol definition implies stateful servers because -the server maintains a list of client's mount requests. The mount -list information is not critical for the correct functioning of -either the client or the server. It is intended for advisory use -only, for example, to warn possible clients when a server is going -down. -.LP -Version one of the mount protocol is used with version two of the NFS -protocol. The only connecting point is the -.I fhandle -structure, which is the same for both protocols. -.NH 2 -\&RPC Information -.IX "mount protocol" "RPC information" -.IP \fIAuthentication\fP -The mount service uses -.I AUTH_UNIX -and -.I AUTH_DES -style authentication only. -.IP "\fITransport Protocols\fP" -The mount service is currently supported on UDP/IP only. -.IP "\fIPort Number\fP" -Consult the server's portmapper, described in the chapter -.I "Remote Procedure Calls: Protocol Specification", -to find the port number on which the mount service is registered. -.NH 2 -\&Sizes of XDR Structures -.IX "mount protocol" "XDR structure sizes" -.LP -These are the sizes, given in decimal bytes, of various XDR -structures used in the protocol: -.DS -/* \fIThe maximum number of bytes in a pathname argument\fP */ -const MNTPATHLEN = 1024; - -/* \fIThe maximum number of bytes in a name argument\fP */ -const MNTNAMLEN = 255; - -/* \fIThe size in bytes of the opaque file handle\fP */ -const FHSIZE = 32; -.DE -.NH 2 -\&Basic Data Types -.IX "mount protocol" "basic data types" -.IX "mount data types" -.LP -This section presents the data types used by the mount protocol. -In many cases they are similar to the types used in NFS. -.KS -.NH 3 -\&fhandle -.IX "mount data types" fhandle "" \fIfhandle\fP -.DS -typedef opaque fhandle[FHSIZE]; -.DE -.KE -The type -.I fhandle -is the file handle that the server passes to the -client. All file operations are done using file handles to refer -to a file or directory. The file handle can contain whatever -information the server needs to distinguish an individual file. -.LP -This is the same as the "fhandle" XDR definition in version 2 of -the NFS protocol; see -.I "Basic Data Types" -in the definition of the NFS protocol, above. -.KS -.NH 3 -\&fhstatus -.IX "mount data types" fhstatus "" \fIfhstatus\fP -.DS -union fhstatus switch (unsigned status) { - case 0: - fhandle directory; - default: - void; -}; -.DE -.KE -The type -.I fhstatus -is a union. If a "status" of zero is returned, -the call completed successfully, and a file handle for the -"directory" follows. A non-zero status indicates some sort of -error. In this case the status is a UNIX error number. -.KS -.NH 3 -\&dirpath -.IX "mount data types" dirpath "" \fIdirpath\fP -.DS -typedef string dirpath<MNTPATHLEN>; -.DE -.KE -The type -.I dirpath -is a server pathname of a directory. -.KS -.NH 3 -\&name -.IX "mount data types" name "" \fIname\fP -.DS -typedef string name<MNTNAMLEN>; -.DE -.KE -The type -.I name -is an arbitrary string used for various names. -.NH 2 -\&Server Procedures -.IX "mount server procedures" -.LP -The following sections define the RPC procedures supplied by a -mount server. -.ie t .DS -.el .DS L -.ft I -/* -* Protocol description for the mount program -*/ -.ft CW - -program MOUNTPROG { -.ft I -/* -* Version 1 of the mount protocol used with -* version 2 of the NFS protocol. -*/ -.ft CW - version MOUNTVERS { - void MOUNTPROC_NULL(void) = 0; - fhstatus MOUNTPROC_MNT(dirpath) = 1; - mountlist MOUNTPROC_DUMP(void) = 2; - void MOUNTPROC_UMNT(dirpath) = 3; - void MOUNTPROC_UMNTALL(void) = 4; - exportlist MOUNTPROC_EXPORT(void) = 5; - } = 1; -} = 100005; -.DE -.KS -.NH 3 -\&Do Nothing -.IX "mount server procedures" MNTPROC_NULL() "" \fIMNTPROC_NULL()\fP -.DS -void -MNTPROC_NULL(void) = 0; -.DE -.KE -This procedure does no work. It is made available in all RPC -services to allow server response testing and timing. -.KS -.NH 3 -\&Add Mount Entry -.IX "mount server procedures" MNTPROC_MNT() "" \fIMNTPROC_MNT()\fP -.DS -fhstatus -MNTPROC_MNT(dirpath) = 1; -.DE -.KE -If the reply "status" is 0, then the reply "directory" contains the -file handle for the directory "dirname". This file handle may be -used in the NFS protocol. This procedure also adds a new entry to -the mount list for this client mounting "dirname". -.KS -.NH 3 -\&Return Mount Entries -.IX "mount server procedures" MNTPROC_DUMP() "" \fIMNTPROC_DUMP()\fP -.DS -struct *mountlist { - name hostname; - dirpath directory; - mountlist nextentry; -}; - -mountlist -MNTPROC_DUMP(void) = 2; -.DE -.KE -Returns the list of remote mounted filesystems. The "mountlist" -contains one entry for each "hostname" and "directory" pair. -.KS -.NH 3 -\&Remove Mount Entry -.IX "mount server procedures" MNTPROC_UMNT() "" \fIMNTPROC_UMNT()\fP -.DS -void -MNTPROC_UMNT(dirpath) = 3; -.DE -.KE -Removes the mount list entry for the input "dirpath". -.KS -.NH 3 -\&Remove All Mount Entries -.IX "mount server procedures" MNTPROC_UMNTALL() "" \fIMNTPROC_UMNTALL()\fP -.DS -void -MNTPROC_UMNTALL(void) = 4; -.DE -.KE -Removes all of the mount list entries for this client. -.KS -.NH 3 -\&Return Export List -.IX "mount server procedures" MNTPROC_EXPORT() "" \fIMNTPROC_EXPORT()\fP -.DS -struct *groups { - name grname; - groups grnext; -}; - -struct *exportlist { - dirpath filesys; - groups groups; - exportlist next; -}; - -exportlist -MNTPROC_EXPORT(void) = 5; -.DE -.KE -Returns a variable number of export list entries. Each entry -contains a filesystem name and a list of groups that are allowed to -import it. The filesystem name is in "filesys", and the group name -is in the list "groups". -.LP -Note: The exportlist should contain -more information about the status of the filesystem, such as a -read-only flag. diff --git a/lib/libc/rpc/PSD.doc/rpc.prog.ms b/lib/libc/rpc/PSD.doc/rpc.prog.ms deleted file mode 100644 index 8b79130..0000000 --- a/lib/libc/rpc/PSD.doc/rpc.prog.ms +++ /dev/null @@ -1,2686 +0,0 @@ -.\" -.\" Must use -- tbl and pic -- with this one -.\" -.\" @(#)rpc.prog.ms 2.3 88/08/11 4.0 RPCSRC -.\" $FreeBSD$ -.\" -.de BT -.if \\n%=1 .tl ''- % -'' -.. -.nr OF 0 -.ND -.\" prevent excess underlining in nroff -.if n .fp 2 R -.OH 'Remote Procedure Call Programming Guide''Page %' -.EH 'Page %''Remote Procedure Call Programming Guide' -.SH -\&Remote Procedure Call Programming Guide -.nr OF 1 -.IX "Network Programming" "" "" "" PAGE MAJOR -.IX "RPC Programming Guide" -.LP -This document assumes a working knowledge of network theory. It is -intended for programmers who wish to write network applications using -remote procedure calls (explained below), and who want to understand -the RPC mechanisms usually hidden by the -.I rpcgen(1) -protocol compiler. -.I rpcgen -is described in detail in the previous chapter, the -.I "\fBrpcgen\fP \fIProgramming Guide\fP". -.SH -Note: -.I -.IX rpcgen "" \fIrpcgen\fP -Before attempting to write a network application, or to convert an -existing non-network application to run over the network, you may want to -understand the material in this chapter. However, for most applications, -you can circumvent the need to cope with the details presented here by using -.I rpcgen . -The -.I "Generating XDR Routines" -section of that chapter contains the complete source for a working RPC -service\(ema remote directory listing service which uses -.I rpcgen -to generate XDR routines as well as client and server stubs. -.LP -.LP -What are remote procedure calls? Simply put, they are the high-level -communications paradigm used in the operating system. -RPC presumes the existence of -low-level networking mechanisms (such as TCP/IP and UDP/IP), and upon them -it implements a logical client to server communications system designed -specifically for the support of network applications. With RPC, the client -makes a procedure call to send a data packet to the server. When the -packet arrives, the server calls a dispatch routine, performs whatever -service is requested, sends back the reply, and the procedure call returns -to the client. -.NH 0 -\&Layers of RPC -.IX "layers of RPC" -.IX "RPC" "layers" -.LP -The RPC interface can be seen as being divided into three layers.\** -.FS -For a complete specification of the routines in the remote procedure -call Library, see the -.I rpc(3N) -manual page. -.FE -.LP -.I "The Highest Layer:" -.IX RPC "The Highest Layer" -The highest layer is totally transparent to the operating system, -machine and network upon which is is run. It's probably best to -think of this level as a way of -.I using -RPC, rather than as -a \fIpart of\fP RPC proper. Programmers who write RPC routines -should (almost) always make this layer available to others by way -of a simple C front end that entirely hides the networking. -.LP -To illustrate, at this level a program can simply make a call to -.I rnusers (), -a C routine which returns the number of users on a remote machine. -The user is not explicitly aware of using RPC \(em they simply -call a procedure, just as they would call -.I malloc() . -.LP -.I "The Middle Layer:" -.IX RPC "The Middle Layer" -The middle layer is really \*QRPC proper.\*U Here, the user doesn't -need to consider details about sockets, the UNIX system, or other low-level -implementation mechanisms. They simply make remote procedure calls -to routines on other machines. The selling point here is simplicity. -It's this layer that allows RPC to pass the \*Qhello world\*U test \(em -simple things should be simple. The middle-layer routines are used -for most applications. -.LP -RPC calls are made with the system routines -.I registerrpc() -.I callrpc() -and -.I svc_run (). -The first two of these are the most fundamental: -.I registerrpc() -obtains a unique system-wide procedure-identification number, and -.I callrpc() -actually executes a remote procedure call. At the middle level, a -call to -.I rnusers() -is implemented by way of these two routines. -.LP -The middle layer is unfortunately rarely used in serious programming -due to its inflexibility (simplicity). It does not allow timeout -specifications or the choice of transport. It allows no UNIX -process control or flexibility in case of errors. It doesn't support -multiple kinds of call authentication. The programmer rarely needs -all these kinds of control, but one or two of them is often necessary. -.LP -.I "The Lowest Layer:" -.IX RPC "The Lowest Layer" -The lowest layer does allow these details to be controlled by the -programmer, and for that reason it is often necessary. Programs -written at this level are also most efficient, but this is rarely a -real issue \(em since RPC clients and servers rarely generate -heavy network loads. -.LP -Although this document only discusses the interface to C, -remote procedure calls can be made from any language. -Even though this document discusses RPC -when it is used to communicate -between processes on different machines, -it works just as well for communication -between different processes on the same machine. -.br -.KS -.NH 2 -\&The RPC Paradigm -.IX RPC paradigm -.LP -Here is a diagram of the RPC paradigm: -.LP -\fBFigure 1-1\fI Network Communication with the Remote Reocedure Call\fR -.LP -.PS -L1: arrow down 1i "client " rjust "program " rjust -L2: line right 1.5i "\fIcallrpc\fP" "function" -move up 1.5i; line dotted down 6i; move up 4.5i -arrow right 1i -L3: arrow down 1i "invoke " rjust "service " rjust -L4: arrow right 1.5i "call" "service" -L5: arrow down 1i " service" ljust " executes" ljust -L6: arrow left 1.5i "\fIreturn\fP" "answer" -L7: arrow down 1i "request " rjust "completed " rjust -L8: line left 1i -arrow left 1.5i "\fIreturn\fP" "reply" -L9: arrow down 1i "program " rjust "continues " rjust -line dashed down from L2 to L9 -line dashed down from L4 to L7 -line dashed up 1i from L3 "service " rjust "daemon " rjust -arrow dashed down 1i from L8 -move right 1i from L3 -box invis "Machine B" -move left 1.2i from L2; move down -box invis "Machine A" -.PE -.KE -.KS -.NH 1 -\&Higher Layers of RPC -.NH 2 -\&Highest Layer -.IX "highest layer of RPC" -.IX RPC "highest layer" -.LP -Imagine you're writing a program that needs to know -how many users are logged into a remote machine. -You can do this by calling the RPC library routine -.I rnusers() -as illustrated below: -.ie t .DS -.el .DS L -.ft CW -#include <stdio.h> - -main(argc, argv) - int argc; - char **argv; -{ - int num; - - if (argc != 2) { - fprintf(stderr, "usage: rnusers hostname\en"); - exit(1); - } - if ((num = rnusers(argv[1])) < 0) { - fprintf(stderr, "error: rnusers\en"); - exit(-1); - } - printf("%d users on %s\en", num, argv[1]); - exit(0); -} -.DE -.KE -RPC library routines such as -.I rnusers() -are in the RPC services library -.I librpcsvc.a -Thus, the program above should be compiled with -.DS -.ft CW -% cc \fIprogram.c -lrpcsvc\fP -.DE -.I rnusers (), -like the other RPC library routines, is documented in section 3R -of the -.I "System Interface Manual for the Sun Workstation" , -the same section which documents the standard Sun RPC services. -.IX "RPC Services" -See the -.I intro(3R) -manual page for an explanation of the documentation strategy -for these services and their RPC protocols. -.LP -Here are some of the RPC service library routines available to the -C programmer: -.LP -\fBTable 3-3\fI RPC Service Library Routines\fR -.TS -box tab (&) ; -cfI cfI -lfL l . -Routine&Description -_ -.sp .5 -rnusers&Return number of users on remote machine -rusers&Return information about users on remote machine -havedisk&Determine if remote machine has disk -rstats&Get performance data from remote kernel -rwall&Write to specified remote machines -yppasswd&Update user password in Yellow Pages -.TE -.LP -Other RPC services \(em for example -.I ether() -.I mount -.I rquota() -and -.I spray -\(em are not available to the C programmer as library routines. -They do, however, -have RPC program numbers so they can be invoked with -.I callrpc() -which will be discussed in the next section. Most of them also -have compilable -.I rpcgen(1) -protocol description files. (The -.I rpcgen -protocol compiler radically simplifies the process of developing -network applications. -See the \fBrpcgen\fI Programming Guide\fR -for detailed information about -.I rpcgen -and -.I rpcgen -protocol description files). -.KS -.NH 2 -\&Intermediate Layer -.IX "intermediate layer of RPC" -.IX "RPC" "intermediate layer" -.LP -The simplest interface, which explicitly makes RPC calls, uses the -functions -.I callrpc() -and -.I registerrpc() -Using this method, the number of remote users can be gotten as follows: -.ie t .DS -.el .DS L -#include <stdio.h> -#include <rpc/rpc.h> -#include <utmp.h> -#include <rpcsvc/rusers.h> - -main(argc, argv) - int argc; - char **argv; -{ - unsigned long nusers; - int stat; - - if (argc != 2) { - fprintf(stderr, "usage: nusers hostname\en"); - exit(-1); - } - if (stat = callrpc(argv[1], - RUSERSPROG, RUSERSVERS, RUSERSPROC_NUM, - xdr_void, 0, xdr_u_long, &nusers) != 0) { - clnt_perrno(stat); - exit(1); - } - printf("%d users on %s\en", nusers, argv[1]); - exit(0); -} -.DE -.KE -Each RPC procedure is uniquely defined by a program number, -version number, and procedure number. The program number -specifies a group of related remote procedures, each of -which has a different procedure number. Each program also -has a version number, so when a minor change is made to a -remote service (adding a new procedure, for example), a new -program number doesn't have to be assigned. When you want -to call a procedure to find the number of remote users, you -look up the appropriate program, version and procedure numbers -in a manual, just as you look up the name of a memory allocator -when you want to allocate memory. -.LP -The simplest way of making remote procedure calls is with the the RPC -library routine -.I callrpc() -It has eight parameters. The first is the name of the remote server -machine. The next three parameters are the program, version, and procedure -numbers\(emtogether they identify the procedure to be called. -The fifth and sixth parameters are an XDR filter and an argument to -be encoded and passed to the remote procedure. -The final two parameters are a filter for decoding the results -returned by the remote procedure and a pointer to the place where -the procedure's results are to be stored. Multiple arguments and -results are handled by embedding them in structures. If -.I callrpc() -completes successfully, it returns zero; else it returns a nonzero -value. The return codes (of type -.IX "enum clnt_stat (in RPC programming)" "" "\fIenum clnt_stat\fP (in RPC programming)" -cast into an integer) are found in -.I <rpc/clnt.h> . -.LP -Since data types may be represented differently on different machines, -.I callrpc() -needs both the type of the RPC argument, as well as -a pointer to the argument itself (and similarly for the result). For -.I RUSERSPROC_NUM , -the return value is an -.I "unsigned long" -so -.I callrpc() -has -.I xdr_u_long() -as its first return parameter, which says -that the result is of type -.I "unsigned long" -and -.I &nusers -as its second return parameter, -which is a pointer to where the long result will be placed. Since -.I RUSERSPROC_NUM -takes no argument, the argument parameter of -.I callrpc() -is -.I xdr_void (). -.LP -After trying several times to deliver a message, if -.I callrpc() -gets no answer, it returns with an error code. -The delivery mechanism is UDP, -which stands for User Datagram Protocol. -Methods for adjusting the number of retries -or for using a different protocol require you to use the lower -layer of the RPC library, discussed later in this document. -The remote server procedure -corresponding to the above might look like this: -.ie t .DS -.el .DS L -.ft CW -.ft CW -char * -nuser(indata) - char *indata; -{ - unsigned long nusers; - -.ft I - /* - * Code here to compute the number of users - * and place result in variable \fInusers\fP. - */ -.ft CW - return((char *)&nusers); -} -.DE -.LP -It takes one argument, which is a pointer to the input -of the remote procedure call (ignored in our example), -and it returns a pointer to the result. -In the current version of C, -character pointers are the generic pointers, -so both the input argument and the return value are cast to -.I "char *" . -.LP -Normally, a server registers all of the RPC calls it plans -to handle, and then goes into an infinite loop waiting to service requests. -In this example, there is only a single procedure -to register, so the main body of the server would look like this: -.ie t .DS -.el .DS L -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> -#include <utmp.h> -#include <rpcsvc/rusers.h> - -char *nuser(); - -main() -{ - registerrpc(RUSERSPROG, RUSERSVERS, RUSERSPROC_NUM, - nuser, xdr_void, xdr_u_long); - svc_run(); /* \fINever returns\fP */ - fprintf(stderr, "Error: svc_run returned!\en"); - exit(1); -} -.DE -.LP -The -.I registerrpc() -routine registers a C procedure as corresponding to a -given RPC procedure number. The first three parameters, -.I RUSERPROG , -.I RUSERSVERS , -and -.I RUSERSPROC_NUM -are the program, version, and procedure numbers -of the remote procedure to be registered; -.I nuser() -is the name of the local procedure that implements the remote -procedure; and -.I xdr_void() -and -.I xdr_u_long() -are the XDR filters for the remote procedure's arguments and -results, respectively. (Multiple arguments or multiple results -are passed as structures). -.LP -Only the UDP transport mechanism can use -.I registerrpc() -thus, it is always safe in conjunction with calls generated by -.I callrpc() . -.SH -.IX "UDP 8K warning" -Warning: the UDP transport mechanism can only deal with -arguments and results less than 8K bytes in length. -.LP -.LP -After registering the local procedure, the server program's -main procedure calls -.I svc_run (), -the RPC library's remote procedure dispatcher. It is this -function that calls the remote procedures in response to RPC -call messages. Note that the dispatcher takes care of decoding -remote procedure arguments and encoding results, using the XDR -filters specified when the remote procedure was registered. -.NH 2 -\&Assigning Program Numbers -.IX "program number assignment" -.IX "assigning program numbers" -.LP -Program numbers are assigned in groups of -.I 0x20000000 -according to the following chart: -.DS -.ft CW - 0x0 - 0x1fffffff \fRDefined by Sun\fP -0x20000000 - 0x3fffffff \fRDefined by user\fP -0x40000000 - 0x5fffffff \fRTransient\fP -0x60000000 - 0x7fffffff \fRReserved\fP -0x80000000 - 0x9fffffff \fRReserved\fP -0xa0000000 - 0xbfffffff \fRReserved\fP -0xc0000000 - 0xdfffffff \fRReserved\fP -0xe0000000 - 0xffffffff \fRReserved\fP -.ft R -.DE -Sun Microsystems administers the first group of numbers, which -should be identical for all Sun customers. If a customer -develops an application that might be of general interest, that -application should be given an assigned number in the first -range. The second group of numbers is reserved for specific -customer applications. This range is intended primarily for -debugging new programs. The third group is reserved for -applications that generate program numbers dynamically. The -final groups are reserved for future use, and should not be -used. -.LP -To register a protocol specification, send a request by network -mail to -.I rpc@sun -or write to: -.DS -RPC Administrator -Sun Microsystems -2550 Garcia Ave. -Mountain View, CA 94043 -.DE -Please include a compilable -.I rpcgen -\*Q.x\*U file describing your protocol. -You will be given a unique program number in return. -.IX RPC administration -.IX administration "of RPC" -.LP -The RPC program numbers and protocol specifications -of standard Sun RPC services can be -found in the include files in -.I "/usr/include/rpcsvc" . -These services, however, constitute only a small subset -of those which have been registered. The complete list of -registered programs, as of the time when this manual was -printed, is: -.LP -\fBTable 3-2\fI RPC Registered Programs\fR -.TS H -box tab (&) ; -lfBI lfBI lfBI -lfL lfL lfI . -RPC Number&Program&Description -_ -.TH -.sp .5 -100000&PMAPPROG&portmapper -100001&RSTATPROG&remote stats -100002&RUSERSPROG&remote users -100003&NFSPROG&nfs -100004&YPPROG&Yellow Pages -100005&MOUNTPROG&mount daemon -100006&DBXPROG&remote dbx -100007&YPBINDPROG&yp binder -100008&WALLPROG&shutdown msg -100009&YPPASSWDPROG&yppasswd server -100010ÐERSTATPROGðer stats -100011&RQUOTAPROG&disk quotas -100012&SPRAYPROG&spray packets -100013&IBM3270PROG&3270 mapper -100014&IBMRJEPROG&RJE mapper -100015&SELNSVCPROG&selection service -100016&RDATABASEPROG&remote database access -100017&REXECPROG&remote execution -100018&ALICEPROG&Alice Office Automation -100019&SCHEDPROG&scheduling service -100020&LOCKPROG&local lock manager -100021&NETLOCKPROG&network lock manager -100022&X25PROG&x.25 inr protocol -100023&STATMON1PROG&status monitor 1 -100024&STATMON2PROG&status monitor 2 -100025&SELNLIBPROG&selection library -100026&BOOTPARAMPROG&boot parameters service -100027&MAZEPROG&mazewars game -100028&YPUPDATEPROG&yp update -100029&KEYSERVEPROG&key server -100030&SECURECMDPROG&secure login -100031&NETFWDIPROG&nfs net forwarder init -100032&NETFWDTPROG&nfs net forwarder trans -100033&SUNLINKMAP_PROG&sunlink MAP -100034&NETMONPROG&network monitor -100035&DBASEPROG&lightweight database -100036&PWDAUTHPROG&password authorization -100037&TFSPROG&translucent file svc -100038&NSEPROG&nse server -100039&NSE_ACTIVATE_PROG&nse activate daemon -.sp .2i -150001&PCNFSDPROG&pc passwd authorization -.sp .2i -200000&PYRAMIDLOCKINGPROG&Pyramid-locking -200001&PYRAMIDSYS5&Pyramid-sys5 -200002&CADDS_IMAGE&CV cadds_image -.sp .2i -300001&ADT_RFLOCKPROG&ADT file locking -.TE -.NH 2 -\&Passing Arbitrary Data Types -.IX "arbitrary data types" -.LP -In the previous example, the RPC call passes a single -.I "unsigned long" -RPC can handle arbitrary data structures, regardless of -different machines' byte orders or structure layout conventions, -by always converting them to a network standard called -.I "External Data Representation" -(XDR) before -sending them over the wire. -The process of converting from a particular machine representation -to XDR format is called -.I serializing , -and the reverse process is called -.I deserializing . -The type field parameters of -.I callrpc() -and -.I registerrpc() -can be a built-in procedure like -.I xdr_u_long() -in the previous example, or a user supplied one. -XDR has these built-in type routines: -.IX RPC "built-in routines" -.DS -.ft CW -xdr_int() xdr_u_int() xdr_enum() -xdr_long() xdr_u_long() xdr_bool() -xdr_short() xdr_u_short() xdr_wrapstring() -xdr_char() xdr_u_char() -.DE -Note that the routine -.I xdr_string() -exists, but cannot be used with -.I callrpc() -and -.I registerrpc (), -which only pass two parameters to their XDR routines. -.I xdr_wrapstring() -has only two parameters, and is thus OK. It calls -.I xdr_string (). -.LP -As an example of a user-defined type routine, -if you wanted to send the structure -.DS -.ft CW -struct simple { - int a; - short b; -} simple; -.DE -then you would call -.I callrpc() -as -.DS -.ft CW -callrpc(hostname, PROGNUM, VERSNUM, PROCNUM, - xdr_simple, &simple ...); -.DE -where -.I xdr_simple() -is written as: -.ie t .DS -.el .DS L -.ft CW -#include <rpc/rpc.h> - -xdr_simple(xdrsp, simplep) - XDR *xdrsp; - struct simple *simplep; -{ - if (!xdr_int(xdrsp, &simplep->a)) - return (0); - if (!xdr_short(xdrsp, &simplep->b)) - return (0); - return (1); -} -.DE -.LP -An XDR routine returns nonzero (true in the sense of C) if it -completes successfully, and zero otherwise. -A complete description of XDR is in the -.I "XDR Protocol Specification" -section of this manual, only few implementation examples are -given here. -.LP -In addition to the built-in primitives, -there are also the prefabricated building blocks: -.DS -.ft CW -xdr_array() xdr_bytes() xdr_reference() -xdr_vector() xdr_union() xdr_pointer() -xdr_string() xdr_opaque() -.DE -To send a variable array of integers, -you might package them up as a structure like this -.DS -.ft CW -struct varintarr { - int *data; - int arrlnth; -} arr; -.DE -and make an RPC call such as -.DS -.ft CW -callrpc(hostname, PROGNUM, VERSNUM, PROCNUM, - xdr_varintarr, &arr...); -.DE -with -.I xdr_varintarr() -defined as: -.ie t .DS -.el .DS L -.ft CW -xdr_varintarr(xdrsp, arrp) - XDR *xdrsp; - struct varintarr *arrp; -{ - return (xdr_array(xdrsp, &arrp->data, &arrp->arrlnth, - MAXLEN, sizeof(int), xdr_int)); -} -.DE -This routine takes as parameters the XDR handle, -a pointer to the array, a pointer to the size of the array, -the maximum allowable array size, -the size of each array element, -and an XDR routine for handling each array element. -.KS -.LP -If the size of the array is known in advance, one can use -.I xdr_vector (), -which serializes fixed-length arrays. -.ie t .DS -.el .DS L -.ft CW -int intarr[SIZE]; - -xdr_intarr(xdrsp, intarr) - XDR *xdrsp; - int intarr[]; -{ - int i; - - return (xdr_vector(xdrsp, intarr, SIZE, sizeof(int), - xdr_int)); -} -.DE -.KE -.LP -XDR always converts quantities to 4-byte multiples when serializing. -Thus, if either of the examples above involved characters -instead of integers, each character would occupy 32 bits. -That is the reason for the XDR routine -.I xdr_bytes() -which is like -.I xdr_array() -except that it packs characters; -.I xdr_bytes() -has four parameters, similar to the first four parameters of -.I xdr_array (). -For null-terminated strings, there is also the -.I xdr_string() -routine, which is the same as -.I xdr_bytes() -without the length parameter. -On serializing it gets the string length from -.I strlen (), -and on deserializing it creates a null-terminated string. -.LP -Here is a final example that calls the previously written -.I xdr_simple() -as well as the built-in functions -.I xdr_string() -and -.I xdr_reference (), -which chases pointers: -.ie t .DS -.el .DS L -.ft CW -struct finalexample { - char *string; - struct simple *simplep; -} finalexample; - -xdr_finalexample(xdrsp, finalp) - XDR *xdrsp; - struct finalexample *finalp; -{ - - if (!xdr_string(xdrsp, &finalp->string, MAXSTRLEN)) - return (0); - if (!xdr_reference(xdrsp, &finalp->simplep, - sizeof(struct simple), xdr_simple); - return (0); - return (1); -} -.DE -Note that we could as easily call -.I xdr_simple() -here instead of -.I xdr_reference (). -.NH 1 -\&Lowest Layer of RPC -.IX "lowest layer of RPC" -.IX "RPC" "lowest layer" -.LP -In the examples given so far, -RPC takes care of many details automatically for you. -In this section, we'll show you how you can change the defaults -by using lower layers of the RPC library. -It is assumed that you are familiar with sockets -and the system calls for dealing with them. -.LP -There are several occasions when you may need to use lower layers of -RPC. First, you may need to use TCP, since the higher layer uses UDP, -which restricts RPC calls to 8K bytes of data. Using TCP permits calls -to send long streams of data. -For an example, see the -.I TCP -section below. Second, you may want to allocate and free memory -while serializing or deserializing with XDR routines. -There is no call at the higher level to let -you free memory explicitly. -For more explanation, see the -.I "Memory Allocation with XDR" -section below. -Third, you may need to perform authentication -on either the client or server side, by supplying -credentials or verifying them. -See the explanation in the -.I Authentication -section below. -.NH 2 -\&More on the Server Side -.IX RPC "server side" -.LP -The server for the -.I nusers() -program shown below does the same thing as the one using -.I registerrpc() -above, but is written using a lower layer of the RPC package: -.ie t .DS -.el .DS L -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> -#include <utmp.h> -#include <rpcsvc/rusers.h> - -main() -{ - SVCXPRT *transp; - int nuser(); - - transp = svcudp_create(RPC_ANYSOCK); - if (transp == NULL){ - fprintf(stderr, "can't create an RPC server\en"); - exit(1); - } - pmap_unset(RUSERSPROG, RUSERSVERS); - if (!svc_register(transp, RUSERSPROG, RUSERSVERS, - nuser, IPPROTO_UDP)) { - fprintf(stderr, "can't register RUSER service\en"); - exit(1); - } - svc_run(); /* \fINever returns\fP */ - fprintf(stderr, "should never reach this point\en"); -} - -nuser(rqstp, transp) - struct svc_req *rqstp; - SVCXPRT *transp; -{ - unsigned long nusers; - - switch (rqstp->rq_proc) { - case NULLPROC: - if (!svc_sendreply(transp, xdr_void, 0)) - fprintf(stderr, "can't reply to RPC call\en"); - return; - case RUSERSPROC_NUM: -.ft I - /* - * Code here to compute the number of users - * and assign it to the variable \fInusers\fP - */ -.ft CW - if (!svc_sendreply(transp, xdr_u_long, &nusers)) - fprintf(stderr, "can't reply to RPC call\en"); - return; - default: - svcerr_noproc(transp); - return; - } -} -.DE -.LP -First, the server gets a transport handle, which is used -for receiving and replying to RPC messages. -.I registerrpc() -uses -.I svcudp_create() -to get a UDP handle. -If you require a more reliable protocol, call -.I svctcp_create() -instead. -If the argument to -.I svcudp_create() -is -.I RPC_ANYSOCK -the RPC library creates a socket -on which to receive and reply to RPC calls. Otherwise, -.I svcudp_create() -expects its argument to be a valid socket number. -If you specify your own socket, it can be bound or unbound. -If it is bound to a port by the user, the port numbers of -.I svcudp_create() -and -.I clnttcp_create() -(the low-level client routine) must match. -.LP -If the user specifies the -.I RPC_ANYSOCK -argument, the RPC library routines will open sockets. -Otherwise they will expect the user to do so. The routines -.I svcudp_create() -and -.I clntudp_create() -will cause the RPC library routines to -.I bind() -their socket if it is not bound already. -.LP -A service may choose to register its port number with the -local portmapper service. This is done is done by specifying -a non-zero protocol number in -.I svc_register (). -Incidently, a client can discover the server's port number by -consulting the portmapper on their server's machine. This can -be done automatically by specifying a zero port number in -.I clntudp_create() -or -.I clnttcp_create (). -.LP -After creating an -.I SVCXPRT , -the next step is to call -.I pmap_unset() -so that if the -.I nusers() -server crashed earlier, -any previous trace of it is erased before restarting. -More precisely, -.I pmap_unset() -erases the entry for -.I RUSERSPROG -from the port mapper's tables. -.LP -Finally, we associate the program number for -.I nusers() -with the procedure -.I nuser (). -The final argument to -.I svc_register() -is normally the protocol being used, -which, in this case, is -.I IPPROTO_UDP -Notice that unlike -.I registerrpc (), -there are no XDR routines involved -in the registration process. -Also, registration is done on the program, -rather than procedure, level. -.LP -The user routine -.I nuser() -must call and dispatch the appropriate XDR routines -based on the procedure number. -Note that -two things are handled by -.I nuser() -that -.I registerrpc() -handles automatically. -The first is that procedure -.I NULLPROC -(currently zero) returns with no results. -This can be used as a simple test -for detecting if a remote program is running. -Second, there is a check for invalid procedure numbers. -If one is detected, -.I svcerr_noproc() -is called to handle the error. -.KS -.LP -The user service routine serializes the results and returns -them to the RPC caller via -.I svc_sendreply() -Its first parameter is the -.I SVCXPRT -handle, the second is the XDR routine, -and the third is a pointer to the data to be returned. -Not illustrated above is how a server -handles an RPC program that receives data. -As an example, we can add a procedure -.I RUSERSPROC_BOOL -which has an argument -.I nusers (), -and returns -.I TRUE -or -.I FALSE -depending on whether there are nusers logged on. -It would look like this: -.ie t .DS -.el .DS L -.ft CW -case RUSERSPROC_BOOL: { - int bool; - unsigned nuserquery; - - if (!svc_getargs(transp, xdr_u_int, &nuserquery) { - svcerr_decode(transp); - return; - } -.ft I - /* - * Code to set \fInusers\fP = number of users - */ -.ft CW - if (nuserquery == nusers) - bool = TRUE; - else - bool = FALSE; - if (!svc_sendreply(transp, xdr_bool, &bool)) { - fprintf(stderr, "can't reply to RPC call\en"); - return (1); - } - return; -} -.DE -.KE -.LP -The relevant routine is -.I svc_getargs() -which takes an -.I SVCXPRT -handle, the XDR routine, -and a pointer to where the input is to be placed as arguments. -.NH 2 -\&Memory Allocation with XDR -.IX "memory allocation with XDR" -.IX XDR "memory allocation" -.LP -XDR routines not only do input and output, -they also do memory allocation. -This is why the second parameter of -.I xdr_array() -is a pointer to an array, rather than the array itself. -If it is -.I NULL , -then -.I xdr_array() -allocates space for the array and returns a pointer to it, -putting the size of the array in the third argument. -As an example, consider the following XDR routine -.I xdr_chararr1() -which deals with a fixed array of bytes with length -.I SIZE . -.ie t .DS -.el .DS L -.ft CW -xdr_chararr1(xdrsp, chararr) - XDR *xdrsp; - char chararr[]; -{ - char *p; - int len; - - p = chararr; - len = SIZE; - return (xdr_bytes(xdrsp, &p, &len, SIZE)); -} -.DE -If space has already been allocated in -.I chararr , -it can be called from a server like this: -.ie t .DS -.el .DS L -.ft CW -char chararr[SIZE]; - -svc_getargs(transp, xdr_chararr1, chararr); -.DE -If you want XDR to do the allocation, -you would have to rewrite this routine in the following way: -.ie t .DS -.el .DS L -.ft CW -xdr_chararr2(xdrsp, chararrp) - XDR *xdrsp; - char **chararrp; -{ - int len; - - len = SIZE; - return (xdr_bytes(xdrsp, charrarrp, &len, SIZE)); -} -.DE -Then the RPC call might look like this: -.ie t .DS -.el .DS L -.ft CW -char *arrptr; - -arrptr = NULL; -svc_getargs(transp, xdr_chararr2, &arrptr); -.ft I -/* - * Use the result here - */ -.ft CW -svc_freeargs(transp, xdr_chararr2, &arrptr); -.DE -Note that, after being used, the character array can be freed with -.I svc_freeargs() -.I svc_freeargs() -will not attempt to free any memory if the variable indicating it -is NULL. For example, in the the routine -.I xdr_finalexample (), -given earlier, if -.I finalp->string -was NULL, then it would not be freed. The same is true for -.I finalp->simplep . -.LP -To summarize, each XDR routine is responsible -for serializing, deserializing, and freeing memory. -When an XDR routine is called from -.I callrpc() -the serializing part is used. -When called from -.I svc_getargs() -the deserializer is used. -And when called from -.I svc_freeargs() -the memory deallocator is used. When building simple examples like those -in this section, a user doesn't have to worry -about the three modes. -See the -.I "External Data Representation: Sun Technical Notes" -for examples of more sophisticated XDR routines that determine -which of the three modes they are in and adjust their behavior accordingly. -.KS -.NH 2 -\&The Calling Side -.IX RPC "calling side" -.LP -When you use -.I callrpc() -you have no control over the RPC delivery -mechanism or the socket used to transport the data. -To illustrate the layer of RPC that lets you adjust these -parameters, consider the following code to call the -.I nusers -service: -.ie t .DS -.el .DS L -.ft CW -.vs 11 -#include <stdio.h> -#include <rpc/rpc.h> -#include <utmp.h> -#include <rpcsvc/rusers.h> -#include <sys/socket.h> -#include <sys/time.h> -#include <netdb.h> - -main(argc, argv) - int argc; - char **argv; -{ - struct hostent *hp; - struct timeval pertry_timeout, total_timeout; - struct sockaddr_in server_addr; - int sock = RPC_ANYSOCK; - register CLIENT *client; - enum clnt_stat clnt_stat; - unsigned long nusers; - - if (argc != 2) { - fprintf(stderr, "usage: nusers hostname\en"); - exit(-1); - } - if ((hp = gethostbyname(argv[1])) == NULL) { - fprintf(stderr, "can't get addr for %s\en",argv[1]); - exit(-1); - } - pertry_timeout.tv_sec = 3; - pertry_timeout.tv_usec = 0; - bcopy(hp->h_addr, (caddr_t)&server_addr.sin_addr, - hp->h_length); - server_addr.sin_family = AF_INET; - server_addr.sin_port = 0; - if ((client = clntudp_create(&server_addr, RUSERSPROG, - RUSERSVERS, pertry_timeout, &sock)) == NULL) { - clnt_pcreateerror("clntudp_create"); - exit(-1); - } - total_timeout.tv_sec = 20; - total_timeout.tv_usec = 0; - clnt_stat = clnt_call(client, RUSERSPROC_NUM, xdr_void, - 0, xdr_u_long, &nusers, total_timeout); - if (clnt_stat != RPC_SUCCESS) { - clnt_perror(client, "rpc"); - exit(-1); - } - clnt_destroy(client); - close(sock); - exit(0); -} -.vs -.DE -.KE -The low-level version of -.I callrpc() -is -.I clnt_call() -which takes a -.I CLIENT -pointer rather than a host name. The parameters to -.I clnt_call() -are a -.I CLIENT -pointer, the procedure number, -the XDR routine for serializing the argument, -a pointer to the argument, -the XDR routine for deserializing the return value, -a pointer to where the return value will be placed, -and the time in seconds to wait for a reply. -.LP -The -.I CLIENT -pointer is encoded with the transport mechanism. -.I callrpc() -uses UDP, thus it calls -.I clntudp_create() -to get a -.I CLIENT -pointer. To get TCP (Transmission Control Protocol), you would use -.I clnttcp_create() . -.LP -The parameters to -.I clntudp_create() -are the server address, the program number, the version number, -a timeout value (between tries), and a pointer to a socket. -The final argument to -.I clnt_call() -is the total time to wait for a response. -Thus, the number of tries is the -.I clnt_call() -timeout divided by the -.I clntudp_create() -timeout. -.LP -Note that the -.I clnt_destroy() -call -always deallocates the space associated with the -.I CLIENT -handle. It closes the socket associated with the -.I CLIENT -handle, however, only if the RPC library opened it. It the -socket was opened by the user, it stays open. This makes it -possible, in cases where there are multiple client handles -using the same socket, to destroy one handle without closing -the socket that other handles are using. -.LP -To make a stream connection, the call to -.I clntudp_create() -is replaced with a call to -.I clnttcp_create() . -.DS -.ft CW -clnttcp_create(&server_addr, prognum, versnum, &sock, - inputsize, outputsize); -.DE -There is no timeout argument; instead, the receive and send buffer -sizes must be specified. When the -.I clnttcp_create() -call is made, a TCP connection is established. -All RPC calls using that -.I CLIENT -handle would use this connection. -The server side of an RPC call using TCP has -.I svcudp_create() -replaced by -.I svctcp_create() . -.DS -.ft CW -transp = svctcp_create(RPC_ANYSOCK, 0, 0); -.DE -The last two arguments to -.I svctcp_create() -are send and receive sizes respectively. If `0' is specified for -either of these, the system chooses a reasonable default. -.KS -.NH 1 -\&Other RPC Features -.IX "RPC" "miscellaneous features" -.IX "miscellaneous RPC features" -.LP -This section discusses some other aspects of RPC -that are occasionally useful. -.NH 2 -\&Select on the Server Side -.IX RPC select() RPC \fIselect()\fP -.IX select() "" \fIselect()\fP "on the server side" -.LP -Suppose a process is processing RPC requests -while performing some other activity. -If the other activity involves periodically updating a data structure, -the process can set an alarm signal before calling -.I svc_run() -But if the other activity -involves waiting on a file descriptor, the -.I svc_run() -call won't work. -The code for -.I svc_run() -is as follows: -.ie t .DS -.el .DS L -.ft CW -.vs 11 -void -svc_run() -{ - fd_set readfds; - int dtbsz = getdtablesize(); - - for (;;) { - readfds = svc_fds; - switch (select(dtbsz, &readfds, NULL,NULL,NULL)) { - - case -1: - if (errno == EINTR) - continue; - perror("select"); - return; - case 0: - break; - default: - svc_getreqset(&readfds); - } - } -} -.vs -.DE -.KE -.LP -You can bypass -.I svc_run() -and call -.I svc_getreqset() -yourself. -All you need to know are the file descriptors -of the socket(s) associated with the programs you are waiting on. -Thus you can have your own -.I select() -.IX select() "" \fIselect()\fP -that waits on both the RPC socket, -and your own descriptors. Note that -.I svc_fds() -is a bit mask of all the file descriptors that RPC is using for -services. It can change everytime that -.I any -RPC library routine is called, because descriptors are constantly -being opened and closed, for example for TCP connections. -.NH 2 -\&Broadcast RPC -.IX "broadcast RPC" -.IX RPC "broadcast" -.LP -The -.I portmapper -is a daemon that converts RPC program numbers -into DARPA protocol port numbers; see the -.I portmap -man page. You can't do broadcast RPC without the portmapper. -Here are the main differences between -broadcast RPC and normal RPC calls: -.IP 1. -Normal RPC expects one answer, whereas -broadcast RPC expects many answers -(one or more answer from each responding machine). -.IP 2. -Broadcast RPC can only be supported by packet-oriented (connectionless) -transport protocols like UPD/IP. -.IP 3. -The implementation of broadcast RPC -treats all unsuccessful responses as garbage by filtering them out. -Thus, if there is a version mismatch between the -broadcaster and a remote service, -the user of broadcast RPC never knows. -.IP 4. -All broadcast messages are sent to the portmap port. -Thus, only services that register themselves with their portmapper -are accessible via the broadcast RPC mechanism. -.IP 5. -Broadcast requests are limited in size to the MTU (Maximum Transfer -Unit) of the local network. For Ethernet, the MTU is 1500 bytes. -.KS -.NH 3 -\&Broadcast RPC Synopsis -.IX "broadcast RPC" synopsis -.IX "RPC" "broadcast synopsis" -.ie t .DS -.el .DS L -.ft CW -#include <rpc/pmap_clnt.h> - . . . -enum clnt_stat clnt_stat; - . . . -clnt_stat = clnt_broadcast(prognum, versnum, procnum, - inproc, in, outproc, out, eachresult) - u_long prognum; /* \fIprogram number\fP */ - u_long versnum; /* \fIversion number\fP */ - u_long procnum; /* \fIprocedure number\fP */ - xdrproc_t inproc; /* \fIxdr routine for args\fP */ - caddr_t in; /* \fIpointer to args\fP */ - xdrproc_t outproc; /* \fIxdr routine for results\fP */ - caddr_t out; /* \fIpointer to results\fP */ - bool_t (*eachresult)();/* \fIcall with each result gotten\fP */ -.DE -.KE -The procedure -.I eachresult() -is called each time a valid result is obtained. -It returns a boolean that indicates -whether or not the user wants more responses. -.ie t .DS -.el .DS L -.ft CW -bool_t done; - . . . -done = eachresult(resultsp, raddr) - caddr_t resultsp; - struct sockaddr_in *raddr; /* \fIAddr of responding machine\fP */ -.DE -If -.I done -is -.I TRUE , -then broadcasting stops and -.I clnt_broadcast() -returns successfully. -Otherwise, the routine waits for another response. -The request is rebroadcast -after a few seconds of waiting. -If no responses come back, -the routine returns with -.I RPC_TIMEDOUT . -.NH 2 -\&Batching -.IX "batching" -.IX RPC "batching" -.LP -The RPC architecture is designed so that clients send a call message, -and wait for servers to reply that the call succeeded. -This implies that clients do not compute -while servers are processing a call. -This is inefficient if the client does not want or need -an acknowledgement for every message sent. -It is possible for clients to continue computing -while waiting for a response, -using RPC batch facilities. -.LP -RPC messages can be placed in a \*Qpipeline\*U of calls -to a desired server; this is called batching. -Batching assumes that: -1) each RPC call in the pipeline requires no response from the server, -and the server does not send a response message; and -2) the pipeline of calls is transported on a reliable -byte stream transport such as TCP/IP. -Since the server does not respond to every call, -the client can generate new calls in parallel -with the server executing previous calls. -Furthermore, the TCP/IP implementation can buffer up -many call messages, and send them to the server in one -.I write() -system call. This overlapped execution -greatly decreases the interprocess communication overhead of -the client and server processes, -and the total elapsed time of a series of calls. -.LP -Since the batched calls are buffered, -the client should eventually do a nonbatched call -in order to flush the pipeline. -.LP -A contrived example of batching follows. -Assume a string rendering service (like a window system) -has two similar calls: one renders a string and returns void results, -while the other renders a string and remains silent. -The service (using the TCP/IP transport) may look like: -.ie t .DS -.el .DS L -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> -#include <suntool/windows.h> - -void windowdispatch(); - -main() -{ - SVCXPRT *transp; - - transp = svctcp_create(RPC_ANYSOCK, 0, 0); - if (transp == NULL){ - fprintf(stderr, "can't create an RPC server\en"); - exit(1); - } - pmap_unset(WINDOWPROG, WINDOWVERS); - if (!svc_register(transp, WINDOWPROG, WINDOWVERS, - windowdispatch, IPPROTO_TCP)) { - fprintf(stderr, "can't register WINDOW service\en"); - exit(1); - } - svc_run(); /* \fINever returns\fP */ - fprintf(stderr, "should never reach this point\en"); -} - -void -windowdispatch(rqstp, transp) - struct svc_req *rqstp; - SVCXPRT *transp; -{ - char *s = NULL; - - switch (rqstp->rq_proc) { - case NULLPROC: - if (!svc_sendreply(transp, xdr_void, 0)) - fprintf(stderr, "can't reply to RPC call\en"); - return; - case RENDERSTRING: - if (!svc_getargs(transp, xdr_wrapstring, &s)) { - fprintf(stderr, "can't decode arguments\en"); -.ft I - /* - * Tell caller he screwed up - */ -.ft CW - svcerr_decode(transp); - break; - } -.ft I - /* - * Code here to render the string \fIs\fP - */ -.ft CW - if (!svc_sendreply(transp, xdr_void, NULL)) - fprintf(stderr, "can't reply to RPC call\en"); - break; - case RENDERSTRING_BATCHED: - if (!svc_getargs(transp, xdr_wrapstring, &s)) { - fprintf(stderr, "can't decode arguments\en"); -.ft I - /* - * We are silent in the face of protocol errors - */ -.ft CW - break; - } -.ft I - /* - * Code here to render string s, but send no reply! - */ -.ft CW - break; - default: - svcerr_noproc(transp); - return; - } -.ft I - /* - * Now free string allocated while decoding arguments - */ -.ft CW - svc_freeargs(transp, xdr_wrapstring, &s); -} -.DE -Of course the service could have one procedure -that takes the string and a boolean -to indicate whether or not the procedure should respond. -.LP -In order for a client to take advantage of batching, -the client must perform RPC calls on a TCP-based transport -and the actual calls must have the following attributes: -1) the result's XDR routine must be zero -.I NULL ), -and 2) the RPC call's timeout must be zero. -.KS -.LP -Here is an example of a client that uses batching to render a -bunch of strings; the batching is flushed when the client gets -a null string (EOF): -.ie t .DS -.el .DS L -.ft CW -.vs 11 -#include <stdio.h> -#include <rpc/rpc.h> -#include <sys/socket.h> -#include <sys/time.h> -#include <netdb.h> -#include <suntool/windows.h> - -main(argc, argv) - int argc; - char **argv; -{ - struct hostent *hp; - struct timeval pertry_timeout, total_timeout; - struct sockaddr_in server_addr; - int sock = RPC_ANYSOCK; - register CLIENT *client; - enum clnt_stat clnt_stat; - char buf[1000], *s = buf; - - if ((client = clnttcp_create(&server_addr, - WINDOWPROG, WINDOWVERS, &sock, 0, 0)) == NULL) { - perror("clnttcp_create"); - exit(-1); - } - total_timeout.tv_sec = 0; - total_timeout.tv_usec = 0; - while (scanf("%s", s) != EOF) { - clnt_stat = clnt_call(client, RENDERSTRING_BATCHED, - xdr_wrapstring, &s, NULL, NULL, total_timeout); - if (clnt_stat != RPC_SUCCESS) { - clnt_perror(client, "batched rpc"); - exit(-1); - } - } - - /* \fINow flush the pipeline\fP */ - - total_timeout.tv_sec = 20; - clnt_stat = clnt_call(client, NULLPROC, xdr_void, NULL, - xdr_void, NULL, total_timeout); - if (clnt_stat != RPC_SUCCESS) { - clnt_perror(client, "rpc"); - exit(-1); - } - clnt_destroy(client); - exit(0); -} -.vs -.DE -.KE -Since the server sends no message, -the clients cannot be notified of any of the failures that may occur. -Therefore, clients are on their own when it comes to handling errors. -.LP -The above example was completed to render -all of the (2000) lines in the file -.I /etc/termcap . -The rendering service did nothing but throw the lines away. -The example was run in the following four configurations: -1) machine to itself, regular RPC; -2) machine to itself, batched RPC; -3) machine to another, regular RPC; and -4) machine to another, batched RPC. -The results are as follows: -1) 50 seconds; -2) 16 seconds; -3) 52 seconds; -4) 10 seconds. -Running -.I fscanf() -on -.I /etc/termcap -only requires six seconds. -These timings show the advantage of protocols -that allow for overlapped execution, -though these protocols are often hard to design. -.NH 2 -\&Authentication -.IX "authentication" -.IX "RPC" "authentication" -.LP -In the examples presented so far, -the caller never identified itself to the server, -and the server never required an ID from the caller. -Clearly, some network services, such as a network filesystem, -require stronger security than what has been presented so far. -.LP -In reality, every RPC call is authenticated by -the RPC package on the server, and similarly, -the RPC client package generates and sends authentication parameters. -Just as different transports (TCP/IP or UDP/IP) -can be used when creating RPC clients and servers, -different forms of authentication can be associated with RPC clients; -the default authentication type used as a default is type -.I none . -.LP -The authentication subsystem of the RPC package is open ended. -That is, numerous types of authentication are easy to support. -.NH 3 -\&UNIX Authentication -.IX "UNIX Authentication" -.IP "\fIThe Client Side\fP" -.LP -When a caller creates a new RPC client handle as in: -.DS -.ft CW -clnt = clntudp_create(address, prognum, versnum, - wait, sockp) -.DE -the appropriate transport instance defaults -the associate authentication handle to be -.DS -.ft CW -clnt->cl_auth = authnone_create(); -.DE -The RPC client can choose to use -.I UNIX -style authentication by setting -.I clnt\->cl_auth -after creating the RPC client handle: -.DS -.ft CW -clnt->cl_auth = authunix_create_default(); -.DE -This causes each RPC call associated with -.I clnt -to carry with it the following authentication credentials structure: -.ie t .DS -.el .DS L -.ft I -/* - * UNIX style credentials. - */ -.ft CW -struct authunix_parms { - u_long aup_time; /* \fIcredentials creation time\fP */ - char *aup_machname; /* \fIhost name where client is\fP */ - int aup_uid; /* \fIclient's UNIX effective uid\fP */ - int aup_gid; /* \fIclient's current group id\fP */ - u_int aup_len; /* \fIelement length of aup_gids\fP */ - int *aup_gids; /* \fIarray of groups user is in\fP */ -}; -.DE -These fields are set by -.I authunix_create_default() -by invoking the appropriate system calls. -Since the RPC user created this new style of authentication, -the user is responsible for destroying it with: -.DS -.ft CW -auth_destroy(clnt->cl_auth); -.DE -This should be done in all cases, to conserve memory. -.sp -.IP "\fIThe Server Side\fP" -.LP -Service implementors have a harder time dealing with authentication issues -since the RPC package passes the service dispatch routine a request -that has an arbitrary authentication style associated with it. -Consider the fields of a request handle passed to a service dispatch routine: -.ie t .DS -.el .DS L -.ft I -/* - * An RPC Service request - */ -.ft CW -struct svc_req { - u_long rq_prog; /* \fIservice program number\fP */ - u_long rq_vers; /* \fIservice protocol vers num\fP */ - u_long rq_proc; /* \fIdesired procedure number\fP */ - struct opaque_auth rq_cred; /* \fIraw credentials from wire\fP */ - caddr_t rq_clntcred; /* \fIcredentials (read only)\fP */ -}; -.DE -The -.I rq_cred -is mostly opaque, except for one field of interest: -the style or flavor of authentication credentials: -.ie t .DS -.el .DS L -.ft I -/* - * Authentication info. Mostly opaque to the programmer. - */ -.ft CW -struct opaque_auth { - enum_t oa_flavor; /* \fIstyle of credentials\fP */ - caddr_t oa_base; /* \fIaddress of more auth stuff\fP */ - u_int oa_length; /* \fInot to exceed \fIMAX_AUTH_BYTES */ -}; -.DE -.IX RPC guarantees -The RPC package guarantees the following -to the service dispatch routine: -.IP 1. -That the request's -.I rq_cred -is well formed. Thus the service implementor may inspect the request's -.I rq_cred.oa_flavor -to determine which style of authentication the caller used. -The service implementor may also wish to inspect the other fields of -.I rq_cred -if the style is not one of the styles supported by the RPC package. -.IP 2. -That the request's -.I rq_clntcred -field is either -.I NULL -or points to a well formed structure -that corresponds to a supported style of authentication credentials. -Remember that only -.I unix -style is currently supported, so (currently) -.I rq_clntcred -could be cast to a pointer to an -.I authunix_parms -structure. If -.I rq_clntcred -is -.I NULL , -the service implementor may wish to inspect the other (opaque) fields of -.I rq_cred -in case the service knows about a new type of authentication -that the RPC package does not know about. -.LP -Our remote users service example can be extended so that -it computes results for all users except UID 16: -.ie t .DS -.el .DS L -.ft CW -.vs 11 -nuser(rqstp, transp) - struct svc_req *rqstp; - SVCXPRT *transp; -{ - struct authunix_parms *unix_cred; - int uid; - unsigned long nusers; - -.ft I - /* - * we don't care about authentication for null proc - */ -.ft CW - if (rqstp->rq_proc == NULLPROC) { - if (!svc_sendreply(transp, xdr_void, 0)) { - fprintf(stderr, "can't reply to RPC call\en"); - return (1); - } - return; - } -.ft I - /* - * now get the uid - */ -.ft CW - switch (rqstp->rq_cred.oa_flavor) { - case AUTH_UNIX: - unix_cred = - (struct authunix_parms *)rqstp->rq_clntcred; - uid = unix_cred->aup_uid; - break; - case AUTH_NULL: - default: - svcerr_weakauth(transp); - return; - } - switch (rqstp->rq_proc) { - case RUSERSPROC_NUM: -.ft I - /* - * make sure caller is allowed to call this proc - */ -.ft CW - if (uid == 16) { - svcerr_systemerr(transp); - return; - } -.ft I - /* - * Code here to compute the number of users - * and assign it to the variable \fInusers\fP - */ -.ft CW - if (!svc_sendreply(transp, xdr_u_long, &nusers)) { - fprintf(stderr, "can't reply to RPC call\en"); - return (1); - } - return; - default: - svcerr_noproc(transp); - return; - } -} -.vs -.DE -A few things should be noted here. -First, it is customary not to check -the authentication parameters associated with the -.I NULLPROC -(procedure number zero). -Second, if the authentication parameter's type is not suitable -for your service, you should call -.I svcerr_weakauth() . -And finally, the service protocol itself should return status -for access denied; in the case of our example, the protocol -does not have such a status, so we call the service primitive -.I svcerr_systemerr() -instead. -.LP -The last point underscores the relation between -the RPC authentication package and the services; -RPC deals only with -.I authentication -and not with individual services' -.I "access control" . -The services themselves must implement their own access control policies -and reflect these policies as return statuses in their protocols. -.NH 2 -\&DES Authentication -.IX RPC DES -.IX RPC authentication -.LP -UNIX authentication is quite easy to defeat. Instead of using -.I authunix_create_default (), -one can call -.I authunix_create() -and then modify the RPC authentication handle it returns by filling in -whatever user ID and hostname they wish the server to think they have. -DES authentication is thus recommended for people who want more security -than UNIX authentication offers. -.LP -The details of the DES authentication protocol are complicated and -are not explained here. -See -.I "Remote Procedure Calls: Protocol Specification" -for the details. -.LP -In order for DES authentication to work, the -.I keyserv(8c) -daemon must be running on both the server and client machines. The -users on these machines need public keys assigned by the network -administrator in the -.I publickey(5) -database. And, they need to have decrypted their secret keys -using their login password. This automatically happens when one -logs in using -.I login(1) , -or can be done manually using -.I keylogin(1) . -The -.I "Network Services" -chapter -.\" XXX -explains more how to setup secure networking. -.sp -.IP "\fIClient Side\fP" -.LP -If a client wishes to use DES authentication, it must set its -authentication handle appropriately. Here is an example: -.DS -cl->cl_auth = - authdes_create(servername, 60, &server_addr, NULL); -.DE -The first argument is the network name or \*Qnetname\*U of the owner of -the server process. Typically, server processes are root processes -and their netname can be derived using the following call: -.DS -char servername[MAXNETNAMELEN]; - -host2netname(servername, rhostname, NULL); -.DE -Here, -.I rhostname -is the hostname of the machine the server process is running on. -.I host2netname() -fills in -.I servername -to contain this root process's netname. If the -server process was run by a regular user, one could use the call -.I user2netname() -instead. Here is an example for a server process with the same user -ID as the client: -.DS -char servername[MAXNETNAMELEN]; - -user2netname(servername, getuid(), NULL); -.DE -The last argument to both of these calls, -.I user2netname() -and -.I host2netname (), -is the name of the naming domain where the server is located. The -.I NULL -used here means \*Quse the local domain name.\*U -.LP -The second argument to -.I authdes_create() -is a lifetime for the credential. Here it is set to sixty -seconds. What that means is that the credential will expire 60 -seconds from now. If some mischievous user tries to reuse the -credential, the server RPC subsystem will recognize that it has -expired and not grant any requests. If the same mischievous user -tries to reuse the credential within the sixty second lifetime, -he will still be rejected because the server RPC subsystem -remembers which credentials it has already seen in the near past, -and will not grant requests to duplicates. -.LP -The third argument to -.I authdes_create() -is the address of the host to synchronize with. In order for DES -authentication to work, the server and client must agree upon the -time. Here we pass the address of the server itself, so the -client and server will both be using the same time: the server's -time. The argument can be -.I NULL , -which means \*Qdon't bother synchronizing.\*U You should only do this -if you are sure the client and server are already synchronized. -.LP -The final argument to -.I authdes_create() -is the address of a DES encryption key to use for encrypting -timestamps and data. If this argument is -.I NULL , -as it is in this example, a random key will be chosen. The client -may find out the encryption key being used by consulting the -.I ah_key -field of the authentication handle. -.sp -.IP "\fIServer Side\fP" -.LP -The server side is a lot simpler than the client side. Here is the -previous example rewritten to use -.I AUTH_DES -instead of -.I AUTH_UNIX : -.ie t .DS -.el .DS L -.ft CW -.vs 11 -#include <sys/time.h> -#include <rpc/auth_des.h> - . . . - . . . -nuser(rqstp, transp) - struct svc_req *rqstp; - SVCXPRT *transp; -{ - struct authdes_cred *des_cred; - int uid; - int gid; - int gidlen; - int gidlist[10]; -.ft I - /* - * we don't care about authentication for null proc - */ -.ft CW - - if (rqstp->rq_proc == NULLPROC) { - /* \fIsame as before\fP */ - } - -.ft I - /* - * now get the uid - */ -.ft CW - switch (rqstp->rq_cred.oa_flavor) { - case AUTH_DES: - des_cred = - (struct authdes_cred *) rqstp->rq_clntcred; - if (! netname2user(des_cred->adc_fullname.name, - &uid, &gid, &gidlen, gidlist)) - { - fprintf(stderr, "unknown user: %s\en", - des_cred->adc_fullname.name); - svcerr_systemerr(transp); - return; - } - break; - case AUTH_NULL: - default: - svcerr_weakauth(transp); - return; - } - -.ft I - /* - * The rest is the same as before - */ -.ft CW -.vs -.DE -Note the use of the routine -.I netname2user (), -the inverse of -.I user2netname (): -it takes a network ID and converts to a unix ID. -.I netname2user () -also supplies the group IDs which we don't use in this example, -but which may be useful to other UNIX programs. -.NH 2 -\&Using Inetd -.IX inetd "" "using \fIinetd\fP" -.LP -An RPC server can be started from -.I inetd -The only difference from the usual code is that the service -creation routine should be called in the following form: -.ie t .DS -.el .DS L -.ft CW -transp = svcudp_create(0); /* \fIFor UDP\fP */ -transp = svctcp_create(0,0,0); /* \fIFor listener TCP sockets\fP */ -transp = svcfd_create(0,0,0); /* \fIFor connected TCP sockets\fP */ -.DE -since -.I inet -passes a socket as file descriptor 0. -Also, -.I svc_register() -should be called as -.ie t .DS -.el .DS L -.ft CW -svc_register(transp, PROGNUM, VERSNUM, service, 0); -.DE -with the final flag as 0, -since the program would already be registered by -.I inetd -Remember that if you want to exit -from the server process and return control to -.I inet -you need to explicitly exit, since -.I svc_run() -never returns. -.LP -The format of entries in -.I /etc/inetd.conf -for RPC services is in one of the following two forms: -.ie t .DS -.el .DS L -.ft CW -p_name/version dgram rpc/udp wait/nowait user server args -p_name/version stream rpc/tcp wait/nowait user server args -.DE -where -.I p_name -is the symbolic name of the program as it appears in -.I rpc(5) , -.I server -is the program implementing the server, -and -.I program -and -.I version -are the program and version numbers of the service. -For more information, see -.I inetd.conf(5) . -.LP -If the same program handles multiple versions, -then the version number can be a range, -as in this example: -.ie t .DS -.el .DS L -.ft CW -rstatd/1-2 dgram rpc/udp wait root /usr/etc/rpc.rstatd -.DE -.NH 1 -\&More Examples -.sp 1 -.NH 2 -\&Versions -.IX "versions" -.IX "RPC" "versions" -.LP -By convention, the first version number of program -.I PROG -is -.I PROGVERS_ORIG -and the most recent version is -.I PROGVERS -Suppose there is a new version of the -.I user -program that returns an -.I "unsigned short" -rather than a -.I long . -If we name this version -.I RUSERSVERS_SHORT -then a server that wants to support both versions -would do a double register. -.ie t .DS -.el .DS L -.ft CW -if (!svc_register(transp, RUSERSPROG, RUSERSVERS_ORIG, - nuser, IPPROTO_TCP)) { - fprintf(stderr, "can't register RUSER service\en"); - exit(1); -} -if (!svc_register(transp, RUSERSPROG, RUSERSVERS_SHORT, - nuser, IPPROTO_TCP)) { - fprintf(stderr, "can't register RUSER service\en"); - exit(1); -} -.DE -Both versions can be handled by the same C procedure: -.ie t .DS -.el .DS L -.ft CW -.vs 11 -nuser(rqstp, transp) - struct svc_req *rqstp; - SVCXPRT *transp; -{ - unsigned long nusers; - unsigned short nusers2; - - switch (rqstp->rq_proc) { - case NULLPROC: - if (!svc_sendreply(transp, xdr_void, 0)) { - fprintf(stderr, "can't reply to RPC call\en"); - return (1); - } - return; - case RUSERSPROC_NUM: -.ft I - /* - * Code here to compute the number of users - * and assign it to the variable \fInusers\fP - */ -.ft CW - nusers2 = nusers; - switch (rqstp->rq_vers) { - case RUSERSVERS_ORIG: - if (!svc_sendreply(transp, xdr_u_long, - &nusers)) { - fprintf(stderr,"can't reply to RPC call\en"); - } - break; - case RUSERSVERS_SHORT: - if (!svc_sendreply(transp, xdr_u_short, - &nusers2)) { - fprintf(stderr,"can't reply to RPC call\en"); - } - break; - } - default: - svcerr_noproc(transp); - return; - } -} -.vs -.DE -.KS -.NH 2 -\&TCP -.IX "TCP" -.LP -Here is an example that is essentially -.I rcp. -The initiator of the RPC -.I snd -call takes its standard input and sends it to the server -.I rcv -which prints it on standard output. -The RPC call uses TCP. -This also illustrates an XDR procedure that behaves differently -on serialization than on deserialization. -.ie t .DS -.el .DS L -.vs 11 -.ft I -/* - * The xdr routine: - * on decode, read from wire, write onto fp - * on encode, read from fp, write onto wire - */ -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> - -xdr_rcp(xdrs, fp) - XDR *xdrs; - FILE *fp; -{ - unsigned long size; - char buf[BUFSIZ], *p; - - if (xdrs->x_op == XDR_FREE)/* nothing to free */ - return 1; - while (1) { - if (xdrs->x_op == XDR_ENCODE) { - if ((size = fread(buf, sizeof(char), BUFSIZ, - fp)) == 0 && ferror(fp)) { - fprintf(stderr, "can't fread\en"); - return (1); - } - } - p = buf; - if (!xdr_bytes(xdrs, &p, &size, BUFSIZ)) - return 0; - if (size == 0) - return 1; - if (xdrs->x_op == XDR_DECODE) { - if (fwrite(buf, sizeof(char), size, - fp) != size) { - fprintf(stderr, "can't fwrite\en"); - return (1); - } - } - } -} -.vs -.DE -.KE -.ie t .DS -.el .DS L -.vs 11 -.ft I -/* - * The sender routines - */ -.ft CW -#include <stdio.h> -#include <netdb.h> -#include <rpc/rpc.h> -#include <sys/socket.h> -#include <sys/time.h> - -main(argc, argv) - int argc; - char **argv; -{ - int xdr_rcp(); - int err; - - if (argc < 2) { - fprintf(stderr, "usage: %s servername\en", argv[0]); - exit(-1); - } - if ((err = callrpctcp(argv[1], RCPPROG, RCPPROC, - RCPVERS, xdr_rcp, stdin, xdr_void, 0) != 0)) { - clnt_perrno(err); - fprintf(stderr, "can't make RPC call\en"); - exit(1); - } - exit(0); -} - -callrpctcp(host, prognum, procnum, versnum, - inproc, in, outproc, out) - char *host, *in, *out; - xdrproc_t inproc, outproc; -{ - struct sockaddr_in server_addr; - int socket = RPC_ANYSOCK; - enum clnt_stat clnt_stat; - struct hostent *hp; - register CLIENT *client; - struct timeval total_timeout; - - if ((hp = gethostbyname(host)) == NULL) { - fprintf(stderr, "can't get addr for '%s'\en", host); - return (-1); - } - bcopy(hp->h_addr, (caddr_t)&server_addr.sin_addr, - hp->h_length); - server_addr.sin_family = AF_INET; - server_addr.sin_port = 0; - if ((client = clnttcp_create(&server_addr, prognum, - versnum, &socket, BUFSIZ, BUFSIZ)) == NULL) { - perror("rpctcp_create"); - return (-1); - } - total_timeout.tv_sec = 20; - total_timeout.tv_usec = 0; - clnt_stat = clnt_call(client, procnum, - inproc, in, outproc, out, total_timeout); - clnt_destroy(client); - return (int)clnt_stat; -} -.vs -.DE -.ie t .DS -.el .DS L -.vs 11 -.ft I -/* - * The receiving routines - */ -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> - -main() -{ - register SVCXPRT *transp; - int rcp_service(), xdr_rcp(); - - if ((transp = svctcp_create(RPC_ANYSOCK, - BUFSIZ, BUFSIZ)) == NULL) { - fprintf("svctcp_create: error\en"); - exit(1); - } - pmap_unset(RCPPROG, RCPVERS); - if (!svc_register(transp, - RCPPROG, RCPVERS, rcp_service, IPPROTO_TCP)) { - fprintf(stderr, "svc_register: error\en"); - exit(1); - } - svc_run(); /* \fInever returns\fP */ - fprintf(stderr, "svc_run should never return\en"); -} - -rcp_service(rqstp, transp) - register struct svc_req *rqstp; - register SVCXPRT *transp; -{ - switch (rqstp->rq_proc) { - case NULLPROC: - if (svc_sendreply(transp, xdr_void, 0) == 0) { - fprintf(stderr, "err: rcp_service"); - return (1); - } - return; - case RCPPROC_FP: - if (!svc_getargs(transp, xdr_rcp, stdout)) { - svcerr_decode(transp); - return; - } - if (!svc_sendreply(transp, xdr_void, 0)) { - fprintf(stderr, "can't reply\en"); - return; - } - return (0); - default: - svcerr_noproc(transp); - return; - } -} -.vs -.DE -.NH 2 -\&Callback Procedures -.IX RPC "callback procedures" -.LP -Occasionally, it is useful to have a server become a client, -and make an RPC call back to the process which is its client. -An example is remote debugging, -where the client is a window system program, -and the server is a debugger running on the remote machine. -Most of the time, -the user clicks a mouse button at the debugging window, -which converts this to a debugger command, -and then makes an RPC call to the server -(where the debugger is actually running), -telling it to execute that command. -However, when the debugger hits a breakpoint, the roles are reversed, -and the debugger wants to make an rpc call to the window program, -so that it can inform the user that a breakpoint has been reached. -.LP -In order to do an RPC callback, -you need a program number to make the RPC call on. -Since this will be a dynamically generated program number, -it should be in the transient range, -.I "0x40000000 - 0x5fffffff" . -The routine -.I gettransient() -returns a valid program number in the transient range, -and registers it with the portmapper. -It only talks to the portmapper running on the same machine as the -.I gettransient() -routine itself. The call to -.I pmap_set() -is a test and set operation, -in that it indivisibly tests whether a program number -has already been registered, -and if it has not, then reserves it. On return, the -.I sockp -argument will contain a socket that can be used -as the argument to an -.I svcudp_create() -or -.I svctcp_create() -call. -.ie t .DS -.el .DS L -.ft CW -.vs 11 -#include <stdio.h> -#include <rpc/rpc.h> -#include <sys/socket.h> - -gettransient(proto, vers, sockp) - int proto, vers, *sockp; -{ - static int prognum = 0x40000000; - int s, len, socktype; - struct sockaddr_in addr; - - switch(proto) { - case IPPROTO_UDP: - socktype = SOCK_DGRAM; - break; - case IPPROTO_TCP: - socktype = SOCK_STREAM; - break; - default: - fprintf(stderr, "unknown protocol type\en"); - return 0; - } - if (*sockp == RPC_ANYSOCK) { - if ((s = socket(AF_INET, socktype, 0)) < 0) { - perror("socket"); - return (0); - } - *sockp = s; - } - else - s = *sockp; - addr.sin_addr.s_addr = 0; - addr.sin_family = AF_INET; - addr.sin_port = 0; - len = sizeof(addr); -.ft I - /* - * may be already bound, so don't check for error - */ -.ft CW - bind(s, &addr, len); - if (getsockname(s, &addr, &len)< 0) { - perror("getsockname"); - return (0); - } - while (!pmap_set(prognum++, vers, proto, - ntohs(addr.sin_port))) continue; - return (prognum-1); -} -.vs -.DE -.SH -Note: -.I -The call to -.I ntohs() -is necessary to ensure that the port number in -.I "addr.sin_port" , -which is in -.I network -byte order, is passed in -.I host -byte order (as -.I pmap_set() -expects). See the -.I byteorder(3N) -man page for more details on the conversion of network -addresses from network to host byte order. -.KS -.LP -The following pair of programs illustrate how to use the -.I gettransient() -routine. -The client makes an RPC call to the server, -passing it a transient program number. -Then the client waits around to receive a callback -from the server at that program number. -The server registers the program -.I EXAMPLEPROG -so that it can receive the RPC call -informing it of the callback program number. -Then at some random time (on receiving an -.I ALRM -signal in this example), it sends a callback RPC call, -using the program number it received earlier. -.ie t .DS -.el .DS L -.vs 11 -.ft I -/* - * client - */ -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> - -int callback(); -char hostname[256]; - -main() -{ - int x, ans, s; - SVCXPRT *xprt; - - gethostname(hostname, sizeof(hostname)); - s = RPC_ANYSOCK; - x = gettransient(IPPROTO_UDP, 1, &s); - fprintf(stderr, "client gets prognum %d\en", x); - if ((xprt = svcudp_create(s)) == NULL) { - fprintf(stderr, "rpc_server: svcudp_create\en"); - exit(1); - } -.ft I - /* protocol is 0 - gettransient does registering - */ -.ft CW - (void)svc_register(xprt, x, 1, callback, 0); - ans = callrpc(hostname, EXAMPLEPROG, EXAMPLEVERS, - EXAMPLEPROC_CALLBACK, xdr_int, &x, xdr_void, 0); - if ((enum clnt_stat) ans != RPC_SUCCESS) { - fprintf(stderr, "call: "); - clnt_perrno(ans); - fprintf(stderr, "\en"); - } - svc_run(); - fprintf(stderr, "Error: svc_run shouldn't return\en"); -} - -callback(rqstp, transp) - register struct svc_req *rqstp; - register SVCXPRT *transp; -{ - switch (rqstp->rq_proc) { - case 0: - if (!svc_sendreply(transp, xdr_void, 0)) { - fprintf(stderr, "err: exampleprog\en"); - return (1); - } - return (0); - case 1: - if (!svc_getargs(transp, xdr_void, 0)) { - svcerr_decode(transp); - return (1); - } - fprintf(stderr, "client got callback\en"); - if (!svc_sendreply(transp, xdr_void, 0)) { - fprintf(stderr, "err: exampleprog"); - return (1); - } - } -} -.vs -.DE -.KE -.ie t .DS -.el .DS L -.vs 11 -.ft I -/* - * server - */ -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> -#include <sys/signal.h> - -char *getnewprog(); -char hostname[256]; -int docallback(); -int pnum; /* \fIprogram number for callback routine\fP */ - -main() -{ - gethostname(hostname, sizeof(hostname)); - registerrpc(EXAMPLEPROG, EXAMPLEVERS, - EXAMPLEPROC_CALLBACK, getnewprog, xdr_int, xdr_void); - fprintf(stderr, "server going into svc_run\en"); - signal(SIGALRM, docallback); - alarm(10); - svc_run(); - fprintf(stderr, "Error: svc_run shouldn't return\en"); -} - -char * -getnewprog(pnump) - char *pnump; -{ - pnum = *(int *)pnump; - return NULL; -} - -docallback() -{ - int ans; - - ans = callrpc(hostname, pnum, 1, 1, xdr_void, 0, - xdr_void, 0); - if (ans != 0) { - fprintf(stderr, "server: "); - clnt_perrno(ans); - fprintf(stderr, "\en"); - } -} -.vs -.DE diff --git a/lib/libc/rpc/PSD.doc/rpc.rfc.ms b/lib/libc/rpc/PSD.doc/rpc.rfc.ms deleted file mode 100644 index 9a948bd..0000000 --- a/lib/libc/rpc/PSD.doc/rpc.rfc.ms +++ /dev/null @@ -1,1304 +0,0 @@ -.\" -.\" Must use -- tbl -- with this one -.\" -.\" @(#)rpc.rfc.ms 2.2 88/08/05 4.0 RPCSRC -.\" $FreeBSD$ -.\" -.de BT -.if \\n%=1 .tl ''- % -'' -.. -.ND -.\" prevent excess underlining in nroff -.if n .fp 2 R -.OH 'Remote Procedure Calls: Protocol Specification''Page %' -.EH 'Page %''Remote Procedure Calls: Protocol Specification' -.if \n%=1 .bp -.SH -\&Remote Procedure Calls: Protocol Specification -.LP -.NH 0 -\&Status of this Memo -.LP -Note: This chapter specifies a protocol that Sun Microsystems, Inc., -and others are using. -It has been designated RFC1050 by the ARPA Network -Information Center. -.LP -.NH 1 -\&Introduction -.LP -This chapter specifies a message protocol used in implementing -Sun's Remote Procedure Call (RPC) package. (The message protocol is -specified with the External Data Representation (XDR) language. -See the -.I "External Data Representation Standard: Protocol Specification" -for the details. Here, we assume that the reader is familiar -with XDR and do not attempt to justify it or its uses). The paper -by Birrell and Nelson [1] is recommended as an excellent background -to and justification of RPC. -.NH 2 -\&Terminology -.LP -This chapter discusses servers, services, programs, procedures, -clients, and versions. A server is a piece of software where network -services are implemented. A network service is a collection of one -or more remote programs. A remote program implements one or more -remote procedures; the procedures, their parameters, and results are -documented in the specific program's protocol specification (see the -\fIPort Mapper Program Protocol\fP\, below, for an example). Network -clients are pieces of software that initiate remote procedure calls -to services. A server may support more than one version of a remote -program in order to be forward compatible with changing protocols. -.LP -For example, a network file service may be composed of two programs. -One program may deal with high-level applications such as file system -access control and locking. The other may deal with low-level file -IO and have procedures like "read" and "write". A client machine of -the network file service would call the procedures associated with -the two programs of the service on behalf of some user on the client -machine. -.NH 2 -\&The RPC Model -.LP -The remote procedure call model is similar to the local procedure -call model. In the local case, the caller places arguments to a -procedure in some well-specified location (such as a result -register). It then transfers control to the procedure, and -eventually gains back control. At that point, the results of the -procedure are extracted from the well-specified location, and the -caller continues execution. -.LP -The remote procedure call is similar, in that one thread of control -logically winds through two processes\(emone is the caller's process, -the other is a server's process. That is, the caller process sends a -call message to the server process and waits (blocks) for a reply -message. The call message contains the procedure's parameters, among -other things. The reply message contains the procedure's results, -among other things. Once the reply message is received, the results -of the procedure are extracted, and caller's execution is resumed. -.LP -On the server side, a process is dormant awaiting the arrival of a -call message. When one arrives, the server process extracts the -procedure's parameters, computes the results, sends a reply message, -and then awaits the next call message. -.LP -Note that in this model, only one of the two processes is active at -any given time. However, this model is only given as an example. -The RPC protocol makes no restrictions on the concurrency model -implemented, and others are possible. For example, an implementation -may choose to have RPC calls be asynchronous, so that the client may -do useful work while waiting for the reply from the server. Another -possibility is to have the server create a task to process an -incoming request, so that the server can be free to receive other -requests. -.NH 2 -\&Transports and Semantics -.LP -The RPC protocol is independent of transport protocols. That is, RPC -does not care how a message is passed from one process to another. -The protocol deals only with specification and interpretation of -messages. -.LP -It is important to point out that RPC does not try to implement any -kind of reliability and that the application must be aware of the -type of transport protocol underneath RPC. If it knows it is running -on top of a reliable transport such as TCP/IP[6], then most of the -work is already done for it. On the other hand, if it is running on -top of an unreliable transport such as UDP/IP[7], it must implement -is own retransmission and time-out policy as the RPC layer does not -provide this service. -.LP -Because of transport independence, the RPC protocol does not attach -specific semantics to the remote procedures or their execution. -Semantics can be inferred from (but should be explicitly specified -by) the underlying transport protocol. For example, consider RPC -running on top of an unreliable transport such as UDP/IP. If an -application retransmits RPC messages after short time-outs, the only -thing it can infer if it receives no reply is that the procedure was -executed zero or more times. If it does receive a reply, then it can -infer that the procedure was executed at least once. -.LP -A server may wish to remember previously granted requests from a -client and not regrant them in order to insure some degree of -execute-at-most-once semantics. A server can do this by taking -advantage of the transaction ID that is packaged with every RPC -request. The main use of this transaction is by the client RPC layer -in matching replies to requests. However, a client application may -choose to reuse its previous transaction ID when retransmitting a -request. The server application, knowing this fact, may choose to -remember this ID after granting a request and not regrant requests -with the same ID in order to achieve some degree of -execute-at-most-once semantics. The server is not allowed to examine -this ID in any other way except as a test for equality. -.LP -On the other hand, if using a reliable transport such as TCP/IP, the -application can infer from a reply message that the procedure was -executed exactly once, but if it receives no reply message, it cannot -assume the remote procedure was not executed. Note that even if a -connection-oriented protocol like TCP is used, an application still -needs time-outs and reconnection to handle server crashes. -.LP -There are other possibilities for transports besides datagram- or -connection-oriented protocols. For example, a request-reply protocol -such as VMTP[2] is perhaps the most natural transport for RPC. -.SH -.I -NOTE: At Sun, RPC is currently implemented on top of both TCP/IP -and UDP/IP transports. -.LP -.NH 2 -\&Binding and Rendezvous Independence -.LP -The act of binding a client to a service is NOT part of the remote -procedure call specification. This important and necessary function -is left up to some higher-level software. (The software may use RPC -itself\(emsee the \fIPort Mapper Program Protocol\fP\, below). -.LP -Implementors should think of the RPC protocol as the jump-subroutine -instruction ("JSR") of a network; the loader (binder) makes JSR -useful, and the loader itself uses JSR to accomplish its task. -Likewise, the network makes RPC useful, using RPC to accomplish this -task. -.NH 2 -\&Authentication -.LP -The RPC protocol provides the fields necessary for a client to -identify itself to a service and vice-versa. Security and access -control mechanisms can be built on top of the message authentication. -Several different authentication protocols can be supported. A field -in the RPC header indicates which protocol is being used. More -information on specific authentication protocols can be found in the -\fIAuthentication Protocols\fP\, -below. -.KS -.NH 1 -\&RPC Protocol Requirements -.LP -The RPC protocol must provide for the following: -.IP 1. -Unique specification of a procedure to be called. -.IP 2. -Provisions for matching response messages to request messages. -.KE -.IP 3. -Provisions for authenticating the caller to service and vice-versa. -.LP -Besides these requirements, features that detect the following are -worth supporting because of protocol roll-over errors, implementation -bugs, user error, and network administration: -.IP 1. -RPC protocol mismatches. -.IP 2. -Remote program protocol version mismatches. -.IP 3. -Protocol errors (such as misspecification of a procedure's parameters). -.IP 4. -Reasons why remote authentication failed. -.IP 5. -Any other reasons why the desired procedure was not called. -.NH 2 -\&Programs and Procedures -.LP -The RPC call message has three unsigned fields: remote program -number, remote program version number, and remote procedure number. -The three fields uniquely identify the procedure to be called. -Program numbers are administered by some central authority (like -Sun). Once an implementor has a program number, he can implement his -remote program; the first implementation would most likely have the -version number of 1. Because most new protocols evolve into better, -stable, and mature protocols, a version field of the call message -identifies which version of the protocol the caller is using. -Version numbers make speaking old and new protocols through the same -server process possible. -.LP -The procedure number identifies the procedure to be called. These -numbers are documented in the specific program's protocol -specification. For example, a file service's protocol specification -may state that its procedure number 5 is "read" and procedure number -12 is "write". -.LP -Just as remote program protocols may change over several versions, -the actual RPC message protocol could also change. Therefore, the -call message also has in it the RPC version number, which is always -equal to two for the version of RPC described here. -.LP -The reply message to a request message has enough information to -distinguish the following error conditions: -.IP 1. -The remote implementation of RPC does speak protocol version 2. -The lowest and highest supported RPC version numbers are returned. -.IP 2. -The remote program is not available on the remote system. -.IP 3. -The remote program does not support the requested version number. -The lowest and highest supported remote program version numbers are -returned. -.IP 4. -The requested procedure number does not exist. (This is usually a -caller side protocol or programming error.) -.IP 5. -The parameters to the remote procedure appear to be garbage from the -server's point of view. (Again, this is usually caused by a -disagreement about the protocol between client and service.) -.NH 2 -\&Authentication -.LP -Provisions for authentication of caller to service and vice-versa are -provided as a part of the RPC protocol. The call message has two -authentication fields, the credentials and verifier. The reply -message has one authentication field, the response verifier. The RPC -protocol specification defines all three fields to be the following -opaque type: -.DS -.ft CW -.vs 11 -enum auth_flavor { - AUTH_NULL = 0, - AUTH_UNIX = 1, - AUTH_SHORT = 2, - AUTH_DES = 3 - /* \fIand more to be defined\fP */ -}; - -struct opaque_auth { - auth_flavor flavor; - opaque body<400>; -}; -.DE -.LP -In simple English, any -.I opaque_auth -structure is an -.I auth_flavor -enumeration followed by bytes which are opaque to the RPC protocol -implementation. -.LP -The interpretation and semantics of the data contained within the -authentication fields is specified by individual, independent -authentication protocol specifications. (See -\fIAuthentication Protocols\fP\, -below, for definitions of the various authentication protocols.) -.LP -If authentication parameters were rejected, the response message -contains information stating why they were rejected. -.NH 2 -\&Program Number Assignment -.LP -Program numbers are given out in groups of -.I 0x20000000 -(decimal 536870912) according to the following chart: -.TS -box tab (&) ; -lfI lfI -rfL cfI . -Program Numbers&Description -_ -.sp .5 -0 - 1fffffff&Defined by Sun -20000000 - 3fffffff&Defined by user -40000000 - 5fffffff&Transient -60000000 - 7fffffff&Reserved -80000000 - 9fffffff&Reserved -a0000000 - bfffffff&Reserved -c0000000 - dfffffff&Reserved -e0000000 - ffffffff&Reserved -.TE -.LP -The first group is a range of numbers administered by Sun -Microsystems and should be identical for all sites. The second range -is for applications peculiar to a particular site. This range is -intended primarily for debugging new programs. When a site develops -an application that might be of general interest, that application -should be given an assigned number in the first range. The third -group is for applications that generate program numbers dynamically. -The final groups are reserved for future use, and should not be used. -.NH 2 -\&Other Uses of the RPC Protocol -.LP -The intended use of this protocol is for calling remote procedures. -That is, each call message is matched with a response message. -However, the protocol itself is a message-passing protocol with which -other (non-RPC) protocols can be implemented. Sun currently uses, or -perhaps abuses, the RPC message protocol for the following two -(non-RPC) protocols: batching (or pipelining) and broadcast RPC. -These two protocols are discussed but not defined below. -.NH 3 -\&Batching -.LP -Batching allows a client to send an arbitrarily large sequence of -call messages to a server; batching typically uses reliable byte -stream protocols (like TCP/IP) for its transport. In the case of -batching, the client never waits for a reply from the server, and the -server does not send replies to batch requests. A sequence of batch -calls is usually terminated by a legitimate RPC in order to flush the -pipeline (with positive acknowledgement). -.NH 3 -\&Broadcast RPC -.LP -In broadcast RPC-based protocols, the client sends a broadcast packet -to the network and waits for numerous replies. Broadcast RPC uses -unreliable, packet-based protocols (like UDP/IP) as its transports. -Servers that support broadcast protocols only respond when the -request is successfully processed, and are silent in the face of -errors. Broadcast RPC uses the Port Mapper RPC service to achieve -its semantics. See the \fIPort Mapper Program Protocol\fP\, below, -for more information. -.KS -.NH 1 -\&The RPC Message Protocol -.LP -This section defines the RPC message protocol in the XDR data -description language. The message is defined in a top-down style. -.ie t .DS -.el .DS L -.ft CW -enum msg_type { - CALL = 0, - REPLY = 1 -}; - -.ft I -/* -* A reply to a call message can take on two forms: -* The message was either accepted or rejected. -*/ -.ft CW -enum reply_stat { - MSG_ACCEPTED = 0, - MSG_DENIED = 1 -}; - -.ft I -/* -* Given that a call message was accepted, the following is the -* status of an attempt to call a remote procedure. -*/ -.ft CW -enum accept_stat { - SUCCESS = 0, /* \fIRPC executed successfully \fP*/ - PROG_UNAVAIL = 1, /* \fIremote hasn't exported program \fP*/ - PROG_MISMATCH = 2, /* \fIremote can't support version # \fP*/ - PROC_UNAVAIL = 3, /* \fIprogram can't support procedure \fP*/ - GARBAGE_ARGS = 4 /* \fIprocedure can't decode params \fP*/ -}; -.DE -.ie t .DS -.el .DS L -.ft I -/* -* Reasons why a call message was rejected: -*/ -.ft CW -enum reject_stat { - RPC_MISMATCH = 0, /* \fIRPC version number != 2 \fP*/ - AUTH_ERROR = 1 /* \fIremote can't authenticate caller \fP*/ -}; - -.ft I -/* -* Why authentication failed: -*/ -.ft CW -enum auth_stat { - AUTH_BADCRED = 1, /* \fIbad credentials \fP*/ - AUTH_REJECTEDCRED = 2, /* \fIclient must begin new session \fP*/ - AUTH_BADVERF = 3, /* \fIbad verifier \fP*/ - AUTH_REJECTEDVERF = 4, /* \fIverifier expired or replayed \fP*/ - AUTH_TOOWEAK = 5 /* \fIrejected for security reasons \fP*/ -}; -.DE -.KE -.ie t .DS -.el .DS L -.ft I -/* -* The RPC message: -* All messages start with a transaction identifier, xid, -* followed by a two-armed discriminated union. The union's -* discriminant is a msg_type which switches to one of the two -* types of the message. The xid of a \fIREPLY\fP message always -* matches that of the initiating \fICALL\fP message. NB: The xid -* field is only used for clients matching reply messages with -* call messages or for servers detecting retransmissions; the -* service side cannot treat this id as any type of sequence -* number. -*/ -.ft CW -struct rpc_msg { - unsigned int xid; - union switch (msg_type mtype) { - case CALL: - call_body cbody; - case REPLY: - reply_body rbody; - } body; -}; -.DE -.ie t .DS -.el .DS L -.ft I -/* -* Body of an RPC request call: -* In version 2 of the RPC protocol specification, rpcvers must -* be equal to 2. The fields prog, vers, and proc specify the -* remote program, its version number, and the procedure within -* the remote program to be called. After these fields are two -* authentication parameters: cred (authentication credentials) -* and verf (authentication verifier). The two authentication -* parameters are followed by the parameters to the remote -* procedure, which are specified by the specific program -* protocol. -*/ -.ft CW -struct call_body { - unsigned int rpcvers; /* \fImust be equal to two (2) \fP*/ - unsigned int prog; - unsigned int vers; - unsigned int proc; - opaque_auth cred; - opaque_auth verf; - /* \fIprocedure specific parameters start here \fP*/ -}; -.DE -.ie t .DS -.el .DS L -.ft I -/* -* Body of a reply to an RPC request: -* The call message was either accepted or rejected. -*/ -.ft CW -union reply_body switch (reply_stat stat) { - case MSG_ACCEPTED: - accepted_reply areply; - case MSG_DENIED: - rejected_reply rreply; -} reply; -.DE -.ie t .DS -.el .DS L -.ft I -/* -* Reply to an RPC request that was accepted by the server: -* there could be an error even though the request was accepted. -* The first field is an authentication verifier that the server -* generates in order to validate itself to the caller. It is -* followed by a union whose discriminant is an enum -* accept_stat. The \fISUCCESS\fP arm of the union is protocol -* specific. The \fIPROG_UNAVAIL\fP, \fIPROC_UNAVAIL\fP, and \fIGARBAGE_ARGP\fP -* arms of the union are void. The \fIPROG_MISMATCH\fP arm specifies -* the lowest and highest version numbers of the remote program -* supported by the server. -*/ -.ft CW -struct accepted_reply { - opaque_auth verf; - union switch (accept_stat stat) { - case SUCCESS: - opaque results[0]; - /* \fIprocedure-specific results start here\fP */ - case PROG_MISMATCH: - struct { - unsigned int low; - unsigned int high; - } mismatch_info; - default: -.ft I - /* - * Void. Cases include \fIPROG_UNAVAIL, PROC_UNAVAIL\fP, - * and \fIGARBAGE_ARGS\fP. - */ -.ft CW - void; - } reply_data; -}; -.DE -.ie t .DS -.el .DS L -.ft I -/* -* Reply to an RPC request that was rejected by the server: -* The request can be rejected for two reasons: either the -* server is not running a compatible version of the RPC -* protocol (\fIRPC_MISMATCH\fP), or the server refuses to -* authenticate the caller (\fIAUTH_ERROR\fP). In case of an RPC -* version mismatch, the server returns the lowest and highest -* supported RPC version numbers. In case of refused -* authentication, failure status is returned. -*/ -.ft CW -union rejected_reply switch (reject_stat stat) { - case RPC_MISMATCH: - struct { - unsigned int low; - unsigned int high; - } mismatch_info; - case AUTH_ERROR: - auth_stat stat; -}; -.DE -.NH 1 -\&Authentication Protocols -.LP -As previously stated, authentication parameters are opaque, but -open-ended to the rest of the RPC protocol. This section defines -some "flavors" of authentication implemented at (and supported by) -Sun. Other sites are free to invent new authentication types, with -the same rules of flavor number assignment as there is for program -number assignment. -.NH 2 -\&Null Authentication -.LP -Often calls must be made where the caller does not know who he is or -the server does not care who the caller is. In this case, the flavor -value (the discriminant of the \fIopaque_auth\fP's union) of the RPC -message's credentials, verifier, and response verifier is -.I AUTH_NULL . -The bytes of the opaque_auth's body are undefined. -It is recommended that the opaque length be zero. -.NH 2 -\&UNIX Authentication -.LP -The caller of a remote procedure may wish to identify himself as he -is identified on a UNIX system. The value of the credential's -discriminant of an RPC call message is -.I AUTH_UNIX . -The bytes of -the credential's opaque body encode the following structure: -.DS -.ft CW -struct auth_unix { - unsigned int stamp; - string machinename<255>; - unsigned int uid; - unsigned int gid; - unsigned int gids<10>; -}; -.DE -The -.I stamp -is an arbitrary ID which the caller machine may -generate. The -.I machinename -is the name of the caller's machine (like "krypton"). The -.I uid -is the caller's effective user ID. The -.I gid -is the caller's effective group ID. The -.I gids -is a -counted array of groups which contain the caller as a member. The -verifier accompanying the credentials should be of -.I AUTH_NULL -(defined above). -.LP -The value of the discriminant of the response verifier received in -the reply message from the server may be -.I AUTH_NULL -or -.I AUTH_SHORT . -In the case of -.I AUTH_SHORT , -the bytes of the response verifier's string encode an opaque -structure. This new opaque structure may now be passed to the server -instead of the original -.I AUTH_UNIX -flavor credentials. The server keeps a cache which maps shorthand -opaque structures (passed back by way of an -.I AUTH_SHORT -style response verifier) to the original credentials of the caller. -The caller can save network bandwidth and server cpu cycles by using -the new credentials. -.LP -The server may flush the shorthand opaque structure at any time. If -this happens, the remote procedure call message will be rejected due -to an authentication error. The reason for the failure will be -.I AUTH_REJECTEDCRED . -At this point, the caller may wish to try the original -.I AUTH_UNIX -style of credentials. -.KS -.NH 2 -\&DES Authentication -.LP -UNIX authentication suffers from two major problems: -.IP 1. -The naming is too UNIX-system oriented. -.IP 2. -There is no verifier, so credentials can easily be faked. -.LP -DES authentication attempts to fix these two problems. -.KE -.NH 3 -\&Naming -.LP -The first problem is handled by addressing the caller by a simple -string of characters instead of by an operating system specific -integer. This string of characters is known as the "netname" or -network name of the caller. The server is not allowed to interpret -the contents of the caller's name in any other way except to -identify the caller. Thus, netnames should be unique for every -caller in the internet. -.LP -It is up to each operating system's implementation of DES -authentication to generate netnames for its users that insure this -uniqueness when they call upon remote servers. Operating systems -already know how to distinguish users local to their systems. It is -usually a simple matter to extend this mechanism to the network. -For example, a UNIX user at Sun with a user ID of 515 might be -assigned the following netname: "unix.515@sun.com". This netname -contains three items that serve to insure it is unique. Going -backwards, there is only one naming domain called "sun.com" in the -internet. Within this domain, there is only one UNIX user with -user ID 515. However, there may be another user on another -operating system, for example VMS, within the same naming domain -that, by coincidence, happens to have the same user ID. To insure -that these two users can be distinguished we add the operating -system name. So one user is "unix.515@sun.com" and the other is -"vms.515@sun.com". -.LP -The first field is actually a naming method rather than an -operating system name. It just happens that today there is almost -a one-to-one correspondence between naming methods and operating -systems. If the world could agree on a naming standard, the first -field could be the name of that standard, instead of an operating -system name. -.LP -.NH 3 -\&DES Authentication Verifiers -.LP -Unlike UNIX authentication, DES authentication does have a verifier -so the server can validate the client's credential (and -vice-versa). The contents of this verifier is primarily an -encrypted timestamp. The server can decrypt this timestamp, and if -it is close to what the real time is, then the client must have -encrypted it correctly. The only way the client could encrypt it -correctly is to know the "conversation key" of the RPC session. And -if the client knows the conversation key, then it must be the real -client. -.LP -The conversation key is a DES [5] key which the client generates -and notifies the server of in its first RPC call. The conversation -key is encrypted using a public key scheme in this first -transaction. The particular public key scheme used in DES -authentication is Diffie-Hellman [3] with 192-bit keys. The -details of this encryption method are described later. -.LP -The client and the server need the same notion of the current time -in order for all of this to work. If network time synchronization -cannot be guaranteed, then client can synchronize with the server -before beginning the conversation, perhaps by consulting the -Internet Time Server (TIME[4]). -.LP -The way a server determines if a client timestamp is valid is -somewhat complicated. For any other transaction but the first, the -server just checks for two things: -.IP 1. -the timestamp is greater than the one previously seen from the -same client. -.IP 2. -the timestamp has not expired. -.LP -A timestamp is expired if the server's time is later than the sum -of the client's timestamp plus what is known as the client's -"window". The "window" is a number the client passes (encrypted) -to the server in its first transaction. You can think of it as a -lifetime for the credential. -.LP -This explains everything but the first transaction. In the first -transaction, the server checks only that the timestamp has not -expired. If this was all that was done though, then it would be -quite easy for the client to send random data in place of the -timestamp with a fairly good chance of succeeding. As an added -check, the client sends an encrypted item in the first transaction -known as the "window verifier" which must be equal to the window -minus 1, or the server will reject the credential. -.LP -The client too must check the verifier returned from the server to -be sure it is legitimate. The server sends back to the client the -encrypted timestamp it received from the client, minus one second. -If the client gets anything different than this, it will reject it. -.LP -.NH 3 -\&Nicknames and Clock Synchronization -.LP -After the first transaction, the server's DES authentication -subsystem returns in its verifier to the client an integer -"nickname" which the client may use in its further transactions -instead of passing its netname, encrypted DES key and window every -time. The nickname is most likely an index into a table on the -server which stores for each client its netname, decrypted DES key -and window. -.LP -Though they originally were synchronized, the client's and server's -clocks can get out of sync again. When this happens the client RPC -subsystem most likely will get back -.I RPC_AUTHERROR -at which point it should resynchronize. -.LP -A client may still get the -.I RPC_AUTHERROR -error even though it is -synchronized with the server. The reason is that the server's -nickname table is a limited size, and it may flush entries whenever -it wants. A client should resend its original credential in this -case and the server will give it a new nickname. If a server -crashes, the entire nickname table gets flushed, and all clients -will have to resend their original credentials. -.KS -.NH 3 -\&DES Authentication Protocol (in XDR language) -.ie t .DS -.el .DS L -.ft I -/* -* There are two kinds of credentials: one in which the client uses -* its full network name, and one in which it uses its "nickname" -* (just an unsigned integer) given to it by the server. The -* client must use its fullname in its first transaction with the -* server, in which the server will return to the client its -* nickname. The client may use its nickname in all further -* transactions with the server. There is no requirement to use the -* nickname, but it is wise to use it for performance reasons. -*/ -.ft CW -enum authdes_namekind { - ADN_FULLNAME = 0, - ADN_NICKNAME = 1 -}; - -.ft I -/* -* A 64-bit block of encrypted DES data -*/ -.ft CW -typedef opaque des_block[8]; - -.ft I -/* -* Maximum length of a network user's name -*/ -.ft CW -const MAXNETNAMELEN = 255; - -.ft I -/* -* A fullname contains the network name of the client, an encrypted -* conversation key and the window. The window is actually a -* lifetime for the credential. If the time indicated in the -* verifier timestamp plus the window has past, then the server -* should expire the request and not grant it. To insure that -* requests are not replayed, the server should insist that -* timestamps are greater than the previous one seen, unless it is -* the first transaction. In the first transaction, the server -* checks instead that the window verifier is one less than the -* window. -*/ -.ft CW -struct authdes_fullname { -string name<MAXNETNAMELEN>; /* \fIname of client \f(CW*/ -des_block key; /* \fIPK encrypted conversation key \f(CW*/ -unsigned int window; /* \fIencrypted window \f(CW*/ -}; - -.ft I -/* -* A credential is either a fullname or a nickname -*/ -.ft CW -union authdes_cred switch (authdes_namekind adc_namekind) { - case ADN_FULLNAME: - authdes_fullname adc_fullname; - case ADN_NICKNAME: - unsigned int adc_nickname; -}; - -.ft I -/* -* A timestamp encodes the time since midnight, January 1, 1970. -*/ -.ft CW -struct timestamp { - unsigned int seconds; /* \fIseconds \fP*/ - unsigned int useconds; /* \fIand microseconds \fP*/ -}; - -.ft I -/* -* Verifier: client variety -* The window verifier is only used in the first transaction. In -* conjunction with a fullname credential, these items are packed -* into the following structure before being encrypted: -* -* \f(CWstruct {\fP -* \f(CWadv_timestamp; \fP-- one DES block -* \f(CWadc_fullname.window; \fP-- one half DES block -* \f(CWadv_winverf; \fP-- one half DES block -* \f(CW}\fP -* This structure is encrypted using CBC mode encryption with an -* input vector of zero. All other encryptions of timestamps use -* ECB mode encryption. -*/ -.ft CW -struct authdes_verf_clnt { - timestamp adv_timestamp; /* \fIencrypted timestamp \fP*/ - unsigned int adv_winverf; /* \fIencrypted window verifier \fP*/ -}; - -.ft I -/* -* Verifier: server variety -* The server returns (encrypted) the same timestamp the client -* gave it minus one second. It also tells the client its nickname -* to be used in future transactions (unencrypted). -*/ -.ft CW -struct authdes_verf_svr { -timestamp adv_timeverf; /* \fIencrypted verifier \fP*/ -unsigned int adv_nickname; /* \fInew nickname for client \fP*/ -}; -.DE -.KE -.NH 3 -\&Diffie-Hellman Encryption -.LP -In this scheme, there are two constants, -.I BASE -and -.I MODULUS . -The -particular values Sun has chosen for these for the DES -authentication protocol are: -.ie t .DS -.el .DS L -.ft CW -const BASE = 3; -const MODULUS = - "d4a0ba0250b6fd2ec626e7efd637df76c716e22d0944b88b"; /* \fIhex \fP*/ -.DE -.ft R -The way this scheme works is best explained by an example. Suppose -there are two people "A" and "B" who want to send encrypted -messages to each other. So, A and B both generate "secret" keys at -random which they do not reveal to anyone. Let these keys be -represented as SK(A) and SK(B). They also publish in a public -directory their "public" keys. These keys are computed as follows: -.ie t .DS -.el .DS L -.ft CW -PK(A) = ( BASE ** SK(A) ) mod MODULUS -PK(B) = ( BASE ** SK(B) ) mod MODULUS -.DE -.ft R -The "**" notation is used here to represent exponentiation. Now, -both A and B can arrive at the "common" key between them, -represented here as CK(A, B), without revealing their secret keys. -.LP -A computes: -.ie t .DS -.el .DS L -.ft CW -CK(A, B) = ( PK(B) ** SK(A)) mod MODULUS -.DE -.ft R -while B computes: -.ie t .DS -.el .DS L -.ft CW -CK(A, B) = ( PK(A) ** SK(B)) mod MODULUS -.DE -.ft R -These two can be shown to be equivalent: -.ie t .DS -.el .DS L -.ft CW -(PK(B) ** SK(A)) mod MODULUS = (PK(A) ** SK(B)) mod MODULUS -.DE -.ft R -We drop the "mod MODULUS" parts and assume modulo arithmetic to -simplify things: -.ie t .DS -.el .DS L -.ft CW -PK(B) ** SK(A) = PK(A) ** SK(B) -.DE -.ft R -Then, replace PK(B) by what B computed earlier and likewise for -PK(A). -.ie t .DS -.el .DS L -.ft CW -((BASE ** SK(B)) ** SK(A) = (BASE ** SK(A)) ** SK(B) -.DE -.ft R -which leads to: -.ie t .DS -.el .DS L -.ft CW -BASE ** (SK(A) * SK(B)) = BASE ** (SK(A) * SK(B)) -.DE -.ft R -This common key CK(A, B) is not used to encrypt the timestamps used -in the protocol. Rather, it is used only to encrypt a conversation -key which is then used to encrypt the timestamps. The reason for -doing this is to use the common key as little as possible, for fear -that it could be broken. Breaking the conversation key is a far -less serious offense, since conversations are relatively -short-lived. -.LP -The conversation key is encrypted using 56-bit DES keys, yet the -common key is 192 bits. To reduce the number of bits, 56 bits are -selected from the common key as follows. The middle-most 8-bytes -are selected from the common key, and then parity is added to the -lower order bit of each byte, producing a 56-bit key with 8 bits of -parity. -.KS -.NH 1 -\&Record Marking Standard -.LP -When RPC messages are passed on top of a byte stream protocol (like -TCP/IP), it is necessary, or at least desirable, to delimit one -message from another in order to detect and possibly recover from -user protocol errors. This is called record marking (RM). Sun uses -this RM/TCP/IP transport for passing RPC messages on TCP streams. -One RPC message fits into one RM record. -.LP -A record is composed of one or more record fragments. A record -fragment is a four-byte header followed by 0 to (2**31) - 1 bytes of -fragment data. The bytes encode an unsigned binary number; as with -XDR integers, the byte order is from highest to lowest. The number -encodes two values\(ema boolean which indicates whether the fragment -is the last fragment of the record (bit value 1 implies the fragment -is the last fragment) and a 31-bit unsigned binary value which is the -length in bytes of the fragment's data. The boolean value is the -highest-order bit of the header; the length is the 31 low-order bits. -(Note that this record specification is NOT in XDR standard form!) -.KE -.KS -.NH 1 -\&The RPC Language -.LP -Just as there was a need to describe the XDR data-types in a formal -language, there is also need to describe the procedures that operate -on these XDR data-types in a formal language as well. We use the RPC -Language for this purpose. It is an extension to the XDR language. -The following example is used to describe the essence of the -language. -.NH 2 -\&An Example Service Described in the RPC Language -.LP -Here is an example of the specification of a simple ping program. -.ie t .DS -.el .DS L -.vs 11 -.ft I -/* -* Simple ping program -*/ -.ft CW -program PING_PROG { - /* \fILatest and greatest version\fP */ - version PING_VERS_PINGBACK { - void - PINGPROC_NULL(void) = 0; - -.ft I - /* - * Ping the caller, return the round-trip time - * (in microseconds). Returns -1 if the operation - * timed out. - */ -.ft CW - int - PINGPROC_PINGBACK(void) = 1; -} = 2; - -.ft I -/* -* Original version -*/ -.ft CW -version PING_VERS_ORIG { - void - PINGPROC_NULL(void) = 0; - } = 1; -} = 1; - -const PING_VERS = 2; /* \fIlatest version \fP*/ -.vs -.DE -.KE -.LP -The first version described is -.I PING_VERS_PINGBACK -with two procedures, -.I PINGPROC_NULL -and -.I PINGPROC_PINGBACK . -.I PINGPROC_NULL -takes no arguments and returns no results, but it is useful for -computing round-trip times from the client to the server and back -again. By convention, procedure 0 of any RPC protocol should have -the same semantics, and never require any kind of authentication. -The second procedure is used for the client to have the server do a -reverse ping operation back to the client, and it returns the amount -of time (in microseconds) that the operation used. The next version, -.I PING_VERS_ORIG , -is the original version of the protocol -and it does not contain -.I PINGPROC_PINGBACK -procedure. It is useful -for compatibility with old client programs, and as this program -matures it may be dropped from the protocol entirely. -.KS -.NH 2 -\&The RPC Language Specification -.LP -The RPC language is identical to the XDR language, except for the -added definition of a -.I program-def -described below. -.DS -.ft CW -program-def: - "program" identifier "{" - version-def - version-def * - "}" "=" constant ";" - -version-def: - "version" identifier "{" - procedure-def - procedure-def * - "}" "=" constant ";" - -procedure-def: - type-specifier identifier "(" type-specifier ")" - "=" constant ";" -.DE -.KE -.NH 2 -\&Syntax Notes -.IP 1. -The following keywords are added and cannot be used as -identifiers: "program" and "version"; -.IP 2. -A version name cannot occur more than once within the scope of -a program definition. Nor can a version number occur more than once -within the scope of a program definition. -.IP 3. -A procedure name cannot occur more than once within the scope -of a version definition. Nor can a procedure number occur more than -once within the scope of version definition. -.IP 4. -Program identifiers are in the same name space as constant and -type identifiers. -.IP 5. -Only unsigned constants can be assigned to programs, versions -and procedures. -.NH 1 -\&Port Mapper Program Protocol -.LP -The port mapper program maps RPC program and version numbers to -transport-specific port numbers. This program makes dynamic binding -of remote programs possible. -.LP -This is desirable because the range of reserved port numbers is very -small and the number of potential remote programs is very large. By -running only the port mapper on a reserved port, the port numbers of -other remote programs can be ascertained by querying the port mapper. -.LP -The port mapper also aids in broadcast RPC. A given RPC program will -usually have different port number bindings on different machines, so -there is no way to directly broadcast to all of these programs. The -port mapper, however, does have a fixed port number. So, to -broadcast to a given program, the client actually sends its message -to the port mapper located at the broadcast address. Each port -mapper that picks up the broadcast then calls the local service -specified by the client. When the port mapper gets the reply from -the local service, it sends the reply on back to the client. -.KS -.NH 2 -\&Port Mapper Protocol Specification (in RPC Language) -.ie t .DS -.el .DS L -.ft CW -.vs 11 -const PMAP_PORT = 111; /* \fIportmapper port number \fP*/ - -.ft I -/* -* A mapping of (program, version, protocol) to port number -*/ -.ft CW -struct mapping { - unsigned int prog; - unsigned int vers; - unsigned int prot; - unsigned int port; -}; - -.ft I -/* -* Supported values for the "prot" field -*/ -.ft CW -const IPPROTO_TCP = 6; /* \fIprotocol number for TCP/IP \fP*/ -const IPPROTO_UDP = 17; /* \fIprotocol number for UDP/IP \fP*/ - -.ft I -/* -* A list of mappings -*/ -.ft CW -struct *pmaplist { - mapping map; - pmaplist next; -}; -.vs -.DE -.ie t .DS -.el .DS L -.vs 11 -.ft I -/* -* Arguments to callit -*/ -.ft CW -struct call_args { - unsigned int prog; - unsigned int vers; - unsigned int proc; - opaque args<>; -}; - -.ft I -/* -* Results of callit -*/ -.ft CW -struct call_result { - unsigned int port; - opaque res<>; -}; -.vs -.DE -.KE -.ie t .DS -.el .DS L -.vs 11 -.ft I -/* -* Port mapper procedures -*/ -.ft CW -program PMAP_PROG { - version PMAP_VERS { - void - PMAPPROC_NULL(void) = 0; - - bool - PMAPPROC_SET(mapping) = 1; - - bool - PMAPPROC_UNSET(mapping) = 2; - - unsigned int - PMAPPROC_GETPORT(mapping) = 3; - - pmaplist - PMAPPROC_DUMP(void) = 4; - - call_result - PMAPPROC_CALLIT(call_args) = 5; - } = 2; -} = 100000; -.vs -.DE -.NH 2 -\&Port Mapper Operation -.LP -The portmapper program currently supports two protocols (UDP/IP and -TCP/IP). The portmapper is contacted by talking to it on assigned -port number 111 (SUNRPC [8]) on either of these protocols. The -following is a description of each of the portmapper procedures: -.IP \fBPMAPPROC_NULL:\fP -This procedure does no work. By convention, procedure zero of any -protocol takes no parameters and returns no results. -.IP \fBPMAPPROC_SET:\fP -When a program first becomes available on a machine, it registers -itself with the port mapper program on the same machine. The program -passes its program number "prog", version number "vers", transport -protocol number "prot", and the port "port" on which it awaits -service request. The procedure returns a boolean response whose -value is -.I TRUE -if the procedure successfully established the mapping and -.I FALSE -otherwise. The procedure refuses to establish -a mapping if one already exists for the tuple "(prog, vers, prot)". -.IP \fBPMAPPROC_UNSET:\fP -When a program becomes unavailable, it should unregister itself with -the port mapper program on the same machine. The parameters and -results have meanings identical to those of -.I PMAPPROC_SET . -The protocol and port number fields of the argument are ignored. -.IP \fBPMAPPROC_GETPORT:\fP -Given a program number "prog", version number "vers", and transport -protocol number "prot", this procedure returns the port number on -which the program is awaiting call requests. A port value of zeros -means the program has not been registered. The "port" field of the -argument is ignored. -.IP \fBPMAPPROC_DUMP:\fP -This procedure enumerates all entries in the port mapper's database. -The procedure takes no parameters and returns a list of program, -version, protocol, and port values. -.IP \fBPMAPPROC_CALLIT:\fP -This procedure allows a caller to call another remote procedure on -the same machine without knowing the remote procedure's port number. -It is intended for supporting broadcasts to arbitrary remote programs -via the well-known port mapper's port. The parameters "prog", -"vers", "proc", and the bytes of "args" are the program number, -version number, procedure number, and parameters of the remote -procedure. -.LP -.B Note: -.RS -.IP 1. -This procedure only sends a response if the procedure was -successfully executed and is silent (no response) otherwise. -.IP 2. -The port mapper communicates with the remote program using UDP/IP -only. -.RE -.LP -The procedure returns the remote program's port number, and the bytes -of results are the results of the remote procedure. -.bp -.NH 1 -\&References -.LP -[1] Birrell, Andrew D. & Nelson, Bruce Jay; "Implementing Remote -Procedure Calls"; XEROX CSL-83-7, October 1983. -.LP -[2] Cheriton, D.; "VMTP: Versatile Message Transaction Protocol", -Preliminary Version 0.3; Stanford University, January 1987. -.LP -[3] Diffie & Hellman; "New Directions in Cryptography"; IEEE -Transactions on Information Theory IT-22, November 1976. -.LP -[4] Harrenstien, K.; "Time Server", RFC 738; Information Sciences -Institute, October 1977. -.LP -[5] National Bureau of Standards; "Data Encryption Standard"; Federal -Information Processing Standards Publication 46, January 1977. -.LP -[6] Postel, J.; "Transmission Control Protocol - DARPA Internet -Program Protocol Specification", RFC 793; Information Sciences -Institute, September 1981. -.LP -[7] Postel, J.; "User Datagram Protocol", RFC 768; Information Sciences -Institute, August 1980. -.LP -[8] Reynolds, J. & Postel, J.; "Assigned Numbers", RFC 923; Information -Sciences Institute, October 1984. diff --git a/lib/libc/rpc/PSD.doc/rpcgen.ms b/lib/libc/rpc/PSD.doc/rpcgen.ms deleted file mode 100644 index e663e7f..0000000 --- a/lib/libc/rpc/PSD.doc/rpcgen.ms +++ /dev/null @@ -1,1301 +0,0 @@ -.\" -.\" Must use -- tbl -- for this one -.\" -.\" @(#)rpcgen.ms 2.2 88/08/04 4.0 RPCSRC -.\" $FreeBSD$ -.\" -.de BT -.if \\n%=1 .tl ''- % -'' -.. -.ND -.\" prevent excess underlining in nroff -.if n .fp 2 R -.OH '\fBrpcgen\fP Programming Guide''Page %' -.EH 'Page %''\fBrpcgen\fP Programming Guide' -.if \n%=1 .bp -.SH -\&\fBrpcgen\fP Programming Guide -.NH 0 -\&The \fBrpcgen\fP Protocol Compiler -.IX rpcgen "" \fIrpcgen\fP "" PAGE MAJOR -.LP -.IX RPC "" "" \fIrpcgen\fP -The details of programming applications to use Remote Procedure Calls -can be overwhelming. Perhaps most daunting is the writing of the XDR -routines necessary to convert procedure arguments and results into -their network format and vice-versa. -.LP -Fortunately, -.I rpcgen(1) -exists to help programmers write RPC applications simply and directly. -.I rpcgen -does most of the dirty work, allowing programmers to debug -the main features of their application, instead of requiring them to -spend most of their time debugging their network interface code. -.LP -.I rpcgen -is a compiler. It accepts a remote program interface definition written -in a language, called RPC Language, which is similar to C. It produces a C -language output which includes stub versions of the client routines, a -server skeleton, XDR filter routines for both parameters and results, and a -header file that contains common definitions. The client stubs interface -with the RPC library and effectively hide the network from their callers. -The server stub similarly hides the network from the server procedures that -are to be invoked by remote clients. -.I rpcgen 's -output files can be compiled and linked in the usual way. The developer -writes server procedures\(emin any language that observes Sun calling -conventions\(emand links them with the server skeleton produced by -.I rpcgen -to get an executable server program. To use a remote program, a programmer -writes an ordinary main program that makes local procedure calls to the -client stubs produced by -.I rpcgen . -Linking this program with -.I rpcgen 's -stubs creates an executable program. (At present the main program must be -written in C). -.I rpcgen -options can be used to suppress stub generation and to specify the transport -to be used by the server stub. -.LP -Like all compilers, -.I rpcgen -reduces development time -that would otherwise be spent coding and debugging low-level routines. -All compilers, including -.I rpcgen , -do this at a small cost in efficiency -and flexibility. However, many compilers allow escape hatches for -programmers to mix low-level code with high-level code. -.I rpcgen -is no exception. In speed-critical applications, hand-written routines -can be linked with the -.I rpcgen -output without any difficulty. Also, one may proceed by using -.I rpcgen -output as a starting point, and then rewriting it as necessary. -(If you need a discussion of RPC programming without -.I rpcgen , -see the -.I "Remote Procedure Call Programming Guide)\. -.NH 1 -\&Converting Local Procedures into Remote Procedures -.IX rpcgen "local procedures" \fIrpcgen\fP -.IX rpcgen "remote procedures" \fIrpcgen\fP -.LP -Assume an application that runs on a single machine, one which we want -to convert to run over the network. Here we will demonstrate such a -conversion by way of a simple example\(ema program that prints a -message to the console: -.ie t .DS -.el .DS L -.ft I -/* - * printmsg.c: print a message on the console - */ -.ft CW -#include <stdio.h> - -main(argc, argv) - int argc; - char *argv[]; -{ - char *message; - - if (argc < 2) { - fprintf(stderr, "usage: %s <message>\en", argv[0]); - exit(1); - } - message = argv[1]; - - if (!printmessage(message)) { - fprintf(stderr, "%s: couldn't print your message\en", - argv[0]); - exit(1); - } - printf("Message Delivered!\en"); - exit(0); -} -.ft I -/* - * Print a message to the console. - * Return a boolean indicating whether the message was actually printed. - */ -.ft CW -printmessage(msg) - char *msg; -{ - FILE *f; - - f = fopen("/dev/console", "w"); - if (f == NULL) { - return (0); - } - fprintf(f, "%s\en", msg); - fclose(f); - return(1); -} -.DE -.LP -And then, of course: -.ie t .DS -.el .DS L -.ft CW -example% \fBcc printmsg.c -o printmsg\fP -example% \fBprintmsg "Hello, there."\fP -Message delivered! -example% -.DE -.LP -If -.I printmessage() -was turned into a remote procedure, -then it could be called from anywhere in the network. -Ideally, one would just like to stick a keyword like -.I remote -in front of a -procedure to turn it into a remote procedure. Unfortunately, -we have to live within the constraints of the C language, since -it existed long before RPC did. But even without language -support, it's not very difficult to make a procedure remote. -.LP -In general, it's necessary to figure out what the types are for -all procedure inputs and outputs. In this case, we have a -procedure -.I printmessage() -which takes a string as input, and returns an integer -as output. Knowing this, we can write a protocol specification in RPC -language that describes the remote version of -.I printmessage (). -Here it is: -.ie t .DS -.el .DS L -.ft I -/* - * msg.x: Remote message printing protocol - */ -.ft CW - -program MESSAGEPROG { - version MESSAGEVERS { - int PRINTMESSAGE(string) = 1; - } = 1; -} = 99; -.DE -.LP -Remote procedures are part of remote programs, so we actually declared -an entire remote program here which contains the single procedure -.I PRINTMESSAGE . -This procedure was declared to be in version 1 of the -remote program. No null procedure (procedure 0) is necessary because -.I rpcgen -generates it automatically. -.LP -Notice that everything is declared with all capital letters. This is -not required, but is a good convention to follow. -.LP -Notice also that the argument type is \*Qstring\*U and not \*Qchar *\*U. This -is because a \*Qchar *\*U in C is ambiguous. Programmers usually intend it -to mean a null-terminated string of characters, but it could also -represent a pointer to a single character or a pointer to an array of -characters. In RPC language, a null-terminated string is -unambiguously called a \*Qstring\*U. -.LP -There are just two more things to write. First, there is the remote -procedure itself. Here's the definition of a remote procedure -to implement the -.I PRINTMESSAGE -procedure we declared above: -.ie t .DS -.el .DS L -.vs 11 -.ft I -/* - * msg_proc.c: implementation of the remote procedure "printmessage" - */ -.ft CW - -#include <stdio.h> -#include <rpc/rpc.h> /* \fIalways needed\fP */ -#include "msg.h" /* \fIneed this too: msg.h will be generated by rpcgen\fP */ - -.ft I -/* - * Remote verson of "printmessage" - */ -.ft CW -int * -printmessage_1(msg) - char **msg; -{ - static int result; /* \fImust be static!\fP */ - FILE *f; - - f = fopen("/dev/console", "w"); - if (f == NULL) { - result = 0; - return (&result); - } - fprintf(f, "%s\en", *msg); - fclose(f); - result = 1; - return (&result); -} -.vs -.DE -.LP -Notice here that the declaration of the remote procedure -.I printmessage_1() -differs from that of the local procedure -.I printmessage() -in three ways: -.IP 1. -It takes a pointer to a string instead of a string itself. This -is true of all remote procedures: they always take pointers to their -arguments rather than the arguments themselves. -.IP 2. -It returns a pointer to an integer instead of an integer itself. This is -also generally true of remote procedures: they always return a pointer -to their results. -.IP 3. -It has an \*Q_1\*U appended to its name. In general, all remote -procedures called by -.I rpcgen -are named by the following rule: the name in the program definition -(here -.I PRINTMESSAGE ) -is converted to all -lower-case letters, an underbar (\*Q_\*U) is appended to it, and -finally the version number (here 1) is appended. -.LP -The last thing to do is declare the main client program that will call -the remote procedure. Here it is: -.ie t .DS -.el .DS L -.ft I -/* - * rprintmsg.c: remote version of "printmsg.c" - */ -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> /* \fIalways needed\fP */ -#include "msg.h" /* \fIneed this too: msg.h will be generated by rpcgen\fP */ - -main(argc, argv) - int argc; - char *argv[]; -{ - CLIENT *cl; - int *result; - char *server; - char *message; - - if (argc < 3) { - fprintf(stderr, "usage: %s host message\en", argv[0]); - exit(1); - } - -.ft I - /* - * Save values of command line arguments - */ -.ft CW - server = argv[1]; - message = argv[2]; - -.ft I - /* - * Create client "handle" used for calling \fIMESSAGEPROG\fP on the - * server designated on the command line. We tell the RPC package - * to use the "tcp" protocol when contacting the server. - */ -.ft CW - cl = clnt_create(server, MESSAGEPROG, MESSAGEVERS, "tcp"); - if (cl == NULL) { -.ft I - /* - * Couldn't establish connection with server. - * Print error message and die. - */ -.ft CW - clnt_pcreateerror(server); - exit(1); - } - -.ft I - /* - * Call the remote procedure "printmessage" on the server - */ -.ft CW - result = printmessage_1(&message, cl); - if (result == NULL) { -.ft I - /* - * An error occurred while calling the server. - * Print error message and die. - */ -.ft CW - clnt_perror(cl, server); - exit(1); - } - -.ft I - /* - * Okay, we successfully called the remote procedure. - */ -.ft CW - if (*result == 0) { -.ft I - /* - * Server was unable to print our message. - * Print error message and die. - */ -.ft CW - fprintf(stderr, "%s: %s couldn't print your message\en", - argv[0], server); - exit(1); - } - -.ft I - /* - * The message got printed on the server's console - */ -.ft CW - printf("Message delivered to %s!\en", server); -} -.DE -There are two things to note here: -.IP 1. -.IX "client handle, used by rpcgen" "" "client handle, used by \fIrpcgen\fP" -First a client \*Qhandle\*U is created using the RPC library routine -.I clnt_create (). -This client handle will be passed to the stub routines -which call the remote procedure. -.IP 2. -The remote procedure -.I printmessage_1() -is called exactly the same way as it is declared in -.I msg_proc.c -except for the inserted client handle as the first argument. -.LP -Here's how to put all of the pieces together: -.ie t .DS -.el .DS L -.ft CW -example% \fBrpcgen msg.x\fP -example% \fBcc rprintmsg.c msg_clnt.c -o rprintmsg\fP -example% \fBcc msg_proc.c msg_svc.c -o msg_server\fP -.DE -Two programs were compiled here: the client program -.I rprintmsg -and the server program -.I msg_server . -Before doing this though, -.I rpcgen -was used to fill in the missing pieces. -.LP -Here is what -.I rpcgen -did with the input file -.I msg.x : -.IP 1. -It created a header file called -.I msg.h -that contained -.I #define 's -for -.I MESSAGEPROG , -.I MESSAGEVERS -and -.I PRINTMESSAGE -for use in the other modules. -.IP 2. -It created client \*Qstub\*U routines in the -.I msg_clnt.c -file. In this case there is only one, the -.I printmessage_1() -that was referred to from the -.I printmsg -client program. The name of the output file for -client stub routines is always formed in this way: if the name of the -input file is -.I FOO.x , -the client stubs output file is called -.I FOO_clnt.c . -.IP 3. -It created the server program which calls -.I printmessage_1() -in -.I msg_proc.c . -This server program is named -.I msg_svc.c . -The rule for naming the server output file is similar to the -previous one: for an input file called -.I FOO.x , -the output server file is named -.I FOO_svc.c . -.LP -Now we're ready to have some fun. First, copy the server to a -remote machine and run it. For this example, the -machine is called \*Qmoon\*U. Server processes are run in the -background, because they never exit. -.ie t .DS -.el .DS L -.ft CW -moon% \fBmsg_server &\fP -.DE -Then on our local machine (\*Qsun\*U) we can print a message on \*Qmoon\*Us -console. -.ie t .DS -.el .DS L -.ft CW -sun% \fBprintmsg moon "Hello, moon."\fP -.DE -The message will get printed to \*Qmoon\*Us console. You can print a -message on anybody's console (including your own) with this program if -you are able to copy the server to their machine and run it. -.NH 1 -\&Generating XDR Routines -.IX RPC "generating XDR routines" -.LP -The previous example only demonstrated the automatic generation of -client and server RPC code. -.I rpcgen -may also be used to generate XDR routines, that is, the routines -necessary to convert local data -structures into network format and vice-versa. This example presents -a complete RPC service\(ema remote directory listing service, which uses -.I rpcgen -not only to generate stub routines, but also to generate the XDR -routines. Here is the protocol description file: -.ie t .DS -.el .DS L -.ft I -/* - * dir.x: Remote directory listing protocol - */ -.ft CW -const MAXNAMELEN = 255; /* \fImaximum length of a directory entry\fP */ - -typedef string nametype<MAXNAMELEN>; /* \fIa directory entry\fP */ - -typedef struct namenode *namelist; /* \fIa link in the listing\fP */ - -.ft I -/* - * A node in the directory listing - */ -.ft CW -struct namenode { - nametype name; /* \fIname of directory entry\fP */ - namelist next; /* \fInext entry\fP */ -}; - -.ft I -/* - * The result of a READDIR operation. - */ -.ft CW -union readdir_res switch (int errno) { -case 0: - namelist list; /* \fIno error: return directory listing\fP */ -default: - void; /* \fIerror occurred: nothing else to return\fP */ -}; - -.ft I -/* - * The directory program definition - */ -.ft CW -program DIRPROG { - version DIRVERS { - readdir_res - READDIR(nametype) = 1; - } = 1; -} = 76; -.DE -.SH -Note: -.I -Types (like -.I readdir_res -in the example above) can be defined using -the \*Qstruct\*U, \*Qunion\*U and \*Qenum\*U keywords, but those keywords -should not be used in subsequent declarations of variables of those types. -For example, if you define a union \*Qfoo\*U, you should declare using -only \*Qfoo\*U and not \*Qunion foo\*U. In fact, -.I rpcgen -compiles -RPC unions into C structures and it is an error to declare them using the -\*Qunion\*U keyword. -.LP -Running -.I rpcgen -on -.I dir.x -creates four output files. Three are the same as before: header file, -client stub routines and server skeleton. The fourth are the XDR routines -necessary for converting the data types we declared into XDR format and -vice-versa. These are output in the file -.I dir_xdr.c . -.LP -Here is the implementation of the -.I READDIR -procedure. -.ie t .DS -.el .DS L -.vs 11 -.ft I -/* - * dir_proc.c: remote readdir implementation - */ -.ft CW -#include <rpc/rpc.h> -#include <sys/dir.h> -#include "dir.h" - -extern int errno; -extern char *malloc(); -extern char *strdup(); - -readdir_res * -readdir_1(dirname) - nametype *dirname; -{ - DIR *dirp; - struct direct *d; - namelist nl; - namelist *nlp; - static readdir_res res; /* \fImust be static\fP! */ - -.ft I - /* - * Open directory - */ -.ft CW - dirp = opendir(*dirname); - if (dirp == NULL) { - res.errno = errno; - return (&res); - } - -.ft I - /* - * Free previous result - */ -.ft CW - xdr_free(xdr_readdir_res, &res); - -.ft I - /* - * Collect directory entries. - * Memory allocated here will be freed by \fIxdr_free\fP - * next time \fIreaddir_1\fP is called - */ -.ft CW - nlp = &res.readdir_res_u.list; - while (d = readdir(dirp)) { - nl = *nlp = (namenode *) malloc(sizeof(namenode)); - nl->name = strdup(d->d_name); - nlp = &nl->next; - } - *nlp = NULL; - -.ft I - /* - * Return the result - */ -.ft CW - res.errno = 0; - closedir(dirp); - return (&res); -} -.vs -.DE -Finally, there is the client side program to call the server: -.ie t .DS -.el .DS L -.ft I -/* - * rls.c: Remote directory listing client - */ -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> /* \fIalways need this\fP */ -#include "dir.h" /* \fIwill be generated by rpcgen\fP */ - -extern int errno; - -main(argc, argv) - int argc; - char *argv[]; -{ - CLIENT *cl; - char *server; - char *dir; - readdir_res *result; - namelist nl; - - - if (argc != 3) { - fprintf(stderr, "usage: %s host directory\en", - argv[0]); - exit(1); - } - -.ft I - /* - * Remember what our command line arguments refer to - */ -.ft CW - server = argv[1]; - dir = argv[2]; - -.ft I - /* - * Create client "handle" used for calling \fIMESSAGEPROG\fP on the - * server designated on the command line. We tell the RPC package - * to use the "tcp" protocol when contacting the server. - */ -.ft CW - cl = clnt_create(server, DIRPROG, DIRVERS, "tcp"); - if (cl == NULL) { -.ft I - /* - * Couldn't establish connection with server. - * Print error message and die. - */ -.ft CW - clnt_pcreateerror(server); - exit(1); - } - -.ft I - /* - * Call the remote procedure \fIreaddir\fP on the server - */ -.ft CW - result = readdir_1(&dir, cl); - if (result == NULL) { -.ft I - /* - * An error occurred while calling the server. - * Print error message and die. - */ -.ft CW - clnt_perror(cl, server); - exit(1); - } - -.ft I - /* - * Okay, we successfully called the remote procedure. - */ -.ft CW - if (result->errno != 0) { -.ft I - /* - * A remote system error occurred. - * Print error message and die. - */ -.ft CW - errno = result->errno; - perror(dir); - exit(1); - } - -.ft I - /* - * Successfully got a directory listing. - * Print it out. - */ -.ft CW - for (nl = result->readdir_res_u.list; nl != NULL; - nl = nl->next) { - printf("%s\en", nl->name); - } - exit(0); -} -.DE -Compile everything, and run. -.DS -.ft CW -sun% \fBrpcgen dir.x\fP -sun% \fBcc rls.c dir_clnt.c dir_xdr.c -o rls\fP -sun% \fBcc dir_svc.c dir_proc.c dir_xdr.c -o dir_svc\fP - -sun% \fBdir_svc &\fP - -moon% \fBrls sun /usr/pub\fP -\&. -\&.. -ascii -eqnchar -greek -kbd -marg8 -tabclr -tabs -tabs4 -moon% -.DE -.LP -.IX "debugging with rpcgen" "" "debugging with \fIrpcgen\fP" -A final note about -.I rpcgen : -The client program and the server procedure can be tested together -as a single program by simply linking them with each other rather -than with the client and server stubs. The procedure calls will be -executed as ordinary local procedure calls and the program can be -debugged with a local debugger such as -.I dbx . -When the program is working, the client program can be linked to -the client stub produced by -.I rpcgen -and the server procedures can be linked to the server stub produced -by -.I rpcgen . -.SH -.I NOTE : -\fIIf you do this, you may want to comment out calls to RPC library -routines, and have client-side routines call server routines -directly.\fP -.LP -.NH 1 -\&The C-Preprocessor -.IX rpcgen "C-preprocessor" \fIrpcgen\fP -.LP -The C-preprocessor is run on all input files before they are -compiled, so all the preprocessor directives are legal within a \*Q.x\*U -file. Four symbols may be defined, depending upon which output file is -getting generated. The symbols are: -.TS -box tab (&); -lfI lfI -lfL l . -Symbol&Usage -_ -RPC_HDR&for header-file output -RPC_XDR&for XDR routine output -RPC_SVC&for server-skeleton output -RPC_CLNT&for client stub output -.TE -.LP -Also, -.I rpcgen -does a little preprocessing of its own. Any line that -begins with a percent sign is passed directly into the output file, -without any interpretation of the line. Here is a simple example that -demonstrates the preprocessing features. -.ie t .DS -.el .DS L -.ft I -/* - * time.x: Remote time protocol - */ -.ft CW -program TIMEPROG { - version TIMEVERS { - unsigned int TIMEGET(void) = 1; - } = 1; -} = 44; - -#ifdef RPC_SVC -%int * -%timeget_1() -%{ -% static int thetime; -% -% thetime = time(0); -% return (&thetime); -%} -#endif -.DE -The '%' feature is not generally recommended, as there is no guarantee -that the compiler will stick the output where you intended. -.NH 1 -\&\fBrpcgen\fP Programming Notes -.IX rpcgen "other operations" \fIrpcgen\fP -.sp -.NH 2 -\&Timeout Changes -.IX rpcgen "timeout changes" \fIrpcgen\fP -.LP -RPC sets a default timeout of 25 seconds for RPC calls when -.I clnt_create() -is used. This timeout may be changed using -.I clnt_control() -Here is a small code fragment to demonstrate use of -.I clnt_control (): -.ID -struct timeval tv; -CLIENT *cl; -.sp .5 -cl = clnt_create("somehost", SOMEPROG, SOMEVERS, "tcp"); -if (cl == NULL) { - exit(1); -} -tv.tv_sec = 60; /* \fIchange timeout to 1 minute\fP */ -tv.tv_usec = 0; -clnt_control(cl, CLSET_TIMEOUT, &tv); -.DE -.NH 2 -\&Handling Broadcast on the Server Side -.IX "broadcast RPC" -.IX rpcgen "broadcast RPC" \fIrpcgen\fP -.LP -When a procedure is known to be called via broadcast RPC, -it is usually wise for the server to not reply unless it can provide -some useful information to the client. This prevents the network -from getting flooded by useless replies. -.LP -To prevent the server from replying, a remote procedure can -return NULL as its result, and the server code generated by -.I rpcgen -will detect this and not send out a reply. -.LP -Here is an example of a procedure that replies only if it -thinks it is an NFS server: -.ID -void * -reply_if_nfsserver() -{ - char notnull; /* \fIjust here so we can use its address\fP */ -.sp .5 - if (access("/etc/exports", F_OK) < 0) { - return (NULL); /* \fIprevent RPC from replying\fP */ - } -.ft I - /* - * return non-null pointer so RPC will send out a reply - */ -.ft L - return ((void *)¬null); -} -.DE -Note that if procedure returns type \*Qvoid *\*U, they must return a non-NULL -pointer if they want RPC to reply for them. -.NH 2 -\&Other Information Passed to Server Procedures -.LP -Server procedures will often want to know more about an RPC call -than just its arguments. For example, getting authentication information -is important to procedures that want to implement some level of security. -This extra information is actually supplied to the server procedure as a -second argument. Here is an example to demonstrate its use. What we've -done here is rewrite the previous -.I printmessage_1() -procedure to only allow root users to print a message to the console. -.ID -int * -printmessage_1(msg, rq) - char **msg; - struct svc_req *rq; -{ - static in result; /* \fIMust be static\fP */ - FILE *f; - struct suthunix_parms *aup; -.sp .5 - aup = (struct authunix_parms *)rq->rq_clntcred; - if (aup->aup_uid != 0) { - result = 0; - return (&result); - } -.sp -.ft I - /* - * Same code as before. - */ -.ft L -} -.DE -.NH 1 -\&RPC Language -.IX RPCL -.IX rpcgen "RPC Language" \fIrpcgen\fP -.LP -RPC language is an extension of XDR language. The sole extension is -the addition of the -.I program -type. For a complete description of the XDR language syntax, see the -.I "External Data Representation Standard: Protocol Specification" -chapter. For a description of the RPC extensions to the XDR language, -see the -.I "Remote Procedure Calls: Protocol Specification" -chapter. -.LP -However, XDR language is so close to C that if you know C, you know most -of it already. We describe here the syntax of the RPC language, -showing a few examples along the way. We also show how the various -RPC and XDR type definitions get compiled into C type definitions in -the output header file. -.KS -.NH 2 -Definitions -\& -.IX rpcgen definitions \fIrpcgen\fP -.LP -An RPC language file consists of a series of definitions. -.DS L -.ft CW - definition-list: - definition ";" - definition ";" definition-list -.DE -.KE -It recognizes five types of definitions. -.DS L -.ft CW - definition: - enum-definition - struct-definition - union-definition - typedef-definition - const-definition - program-definition -.DE -.NH 2 -Structures -\& -.IX rpcgen structures \fIrpcgen\fP -.LP -An XDR struct is declared almost exactly like its C counterpart. It -looks like the following: -.DS L -.ft CW - struct-definition: - "struct" struct-ident "{" - declaration-list - "}" - - declaration-list: - declaration ";" - declaration ";" declaration-list -.DE -As an example, here is an XDR structure to a two-dimensional -coordinate, and the C structure that it gets compiled into in the -output header file. -.DS -.ft CW - struct coord { struct coord { - int x; --> int x; - int y; int y; - }; }; - typedef struct coord coord; -.DE -The output is identical to the input, except for the added -.I typedef -at the end of the output. This allows one to use \*Qcoord\*U instead of -\*Qstruct coord\*U when declaring items. -.NH 2 -Unions -\& -.IX rpcgen unions \fIrpcgen\fP -.LP -XDR unions are discriminated unions, and look quite different from C -unions. They are more analogous to Pascal variant records than they -are to C unions. -.DS L -.ft CW - union-definition: - "union" union-ident "switch" "(" declaration ")" "{" - case-list - "}" - - case-list: - "case" value ":" declaration ";" - "default" ":" declaration ";" - "case" value ":" declaration ";" case-list -.DE -Here is an example of a type that might be returned as the result of a -\*Qread data\*U operation. If there is no error, return a block of data. -Otherwise, don't return anything. -.DS L -.ft CW - union read_result switch (int errno) { - case 0: - opaque data[1024]; - default: - void; - }; -.DE -It gets compiled into the following: -.DS L -.ft CW - struct read_result { - int errno; - union { - char data[1024]; - } read_result_u; - }; - typedef struct read_result read_result; -.DE -Notice that the union component of the output struct has the name as -the type name, except for the trailing \*Q_u\*U. -.NH 2 -Enumerations -\& -.IX rpcgen enumerations \fIrpcgen\fP -.LP -XDR enumerations have the same syntax as C enumerations. -.DS L -.ft CW - enum-definition: - "enum" enum-ident "{" - enum-value-list - "}" - - enum-value-list: - enum-value - enum-value "," enum-value-list - - enum-value: - enum-value-ident - enum-value-ident "=" value -.DE -Here is a short example of an XDR enum, and the C enum that it gets -compiled into. -.DS L -.ft CW - enum colortype { enum colortype { - RED = 0, RED = 0, - GREEN = 1, --> GREEN = 1, - BLUE = 2 BLUE = 2, - }; }; - typedef enum colortype colortype; -.DE -.NH 2 -Typedef -\& -.IX rpcgen typedef \fIrpcgen\fP -.LP -XDR typedefs have the same syntax as C typedefs. -.DS L -.ft CW - typedef-definition: - "typedef" declaration -.DE -Here is an example that defines a -.I fname_type -used for declaring -file name strings that have a maximum length of 255 characters. -.DS L -.ft CW -typedef string fname_type<255>; --> typedef char *fname_type; -.DE -.NH 2 -Constants -\& -.IX rpcgen constants \fIrpcgen\fP -.LP -XDR constants symbolic constants that may be used wherever a -integer constant is used, for example, in array size specifications. -.DS L -.ft CW - const-definition: - "const" const-ident "=" integer -.DE -For example, the following defines a constant -.I DOZEN -equal to 12. -.DS L -.ft CW - const DOZEN = 12; --> #define DOZEN 12 -.DE -.NH 2 -Programs -\& -.IX rpcgen programs \fIrpcgen\fP -.LP -RPC programs are declared using the following syntax: -.DS L -.ft CW - program-definition: - "program" program-ident "{" - version-list - "}" "=" value - - version-list: - version ";" - version ";" version-list - - version: - "version" version-ident "{" - procedure-list - "}" "=" value - - procedure-list: - procedure ";" - procedure ";" procedure-list - - procedure: - type-ident procedure-ident "(" type-ident ")" "=" value -.DE -For example, here is the time protocol, revisited: -.ie t .DS -.el .DS L -.ft I -/* - * time.x: Get or set the time. Time is represented as number of seconds - * since 0:00, January 1, 1970. - */ -.ft CW -program TIMEPROG { - version TIMEVERS { - unsigned int TIMEGET(void) = 1; - void TIMESET(unsigned) = 2; - } = 1; -} = 44; -.DE -This file compiles into #defines in the output header file: -.ie t .DS -.el .DS L -.ft CW -#define TIMEPROG 44 -#define TIMEVERS 1 -#define TIMEGET 1 -#define TIMESET 2 -.DE -.NH 2 -Declarations -\& -.IX rpcgen declarations \fIrpcgen\fP -.LP -In XDR, there are only four kinds of declarations. -.DS L -.ft CW - declaration: - simple-declaration - fixed-array-declaration - variable-array-declaration - pointer-declaration -.DE -\fB1) Simple declarations\fP are just like simple C declarations. -.DS L -.ft CW - simple-declaration: - type-ident variable-ident -.DE -Example: -.DS L -.ft CW - colortype color; --> colortype color; -.DE -\fB2) Fixed-length Array Declarations\fP are just like C array declarations: -.DS L -.ft CW - fixed-array-declaration: - type-ident variable-ident "[" value "]" -.DE -Example: -.DS L -.ft CW - colortype palette[8]; --> colortype palette[8]; -.DE -\fB3) Variable-Length Array Declarations\fP have no explicit syntax -in C, so XDR invents its own using angle-brackets. -.DS L -.ft CW -variable-array-declaration: - type-ident variable-ident "<" value ">" - type-ident variable-ident "<" ">" -.DE -The maximum size is specified between the angle brackets. The size may -be omitted, indicating that the array may be of any size. -.DS L -.ft CW - int heights<12>; /* \fIat most 12 items\fP */ - int widths<>; /* \fIany number of items\fP */ -.DE -Since variable-length arrays have no explicit syntax in C, these -declarations are actually compiled into \*Qstruct\*Us. For example, the -\*Qheights\*U declaration gets compiled into the following struct: -.DS L -.ft CW - struct { - u_int heights_len; /* \fI# of items in array\fP */ - int *heights_val; /* \fIpointer to array\fP */ - } heights; -.DE -Note that the number of items in the array is stored in the \*Q_len\*U -component and the pointer to the array is stored in the \*Q_val\*U -component. The first part of each of these component's names is the -same as the name of the declared XDR variable. -.LP -\fB4) Pointer Declarations\fP are made in -XDR exactly as they are in C. You can't -really send pointers over the network, but you can use XDR pointers -for sending recursive data types such as lists and trees. The type is -actually called \*Qoptional-data\*U, not \*Qpointer\*U, in XDR language. -.DS L -.ft CW - pointer-declaration: - type-ident "*" variable-ident -.DE -Example: -.DS L -.ft CW - listitem *next; --> listitem *next; -.DE -.NH 2 -\&Special Cases -.IX rpcgen "special cases" \fIrpcgen\fP -.LP -There are a few exceptions to the rules described above. -.LP -.B Booleans: -C has no built-in boolean type. However, the RPC library does a -boolean type called -.I bool_t -that is either -.I TRUE -or -.I FALSE . -Things declared as type -.I bool -in XDR language are compiled into -.I bool_t -in the output header file. -.LP -Example: -.DS L -.ft CW - bool married; --> bool_t married; -.DE -.B Strings: -C has no built-in string type, but instead uses the null-terminated -\*Qchar *\*U convention. In XDR language, strings are declared using the -\*Qstring\*U keyword, and compiled into \*Qchar *\*Us in the output header -file. The maximum size contained in the angle brackets specifies the -maximum number of characters allowed in the strings (not counting the -.I NULL -character). The maximum size may be left off, indicating a string -of arbitrary length. -.LP -Examples: -.DS L -.ft CW - string name<32>; --> char *name; - string longname<>; --> char *longname; -.DE -.B "Opaque Data:" -Opaque data is used in RPC and XDR to describe untyped data, that is, -just sequences of arbitrary bytes. It may be declared either as a -fixed or variable length array. -.DS L -Examples: -.ft CW - opaque diskblock[512]; --> char diskblock[512]; - - opaque filedata<1024>; --> struct { - u_int filedata_len; - char *filedata_val; - } filedata; -.DE -.B Voids: -In a void declaration, the variable is not named. The declaration is -just \*Qvoid\*U and nothing else. Void declarations can only occur in two -places: union definitions and program definitions (as the argument or -result of a remote procedure). diff --git a/lib/libc/rpc/PSD.doc/stubs b/lib/libc/rpc/PSD.doc/stubs deleted file mode 100644 index 78b0a2c..0000000 --- a/lib/libc/rpc/PSD.doc/stubs +++ /dev/null @@ -1,3 +0,0 @@ -.\" $FreeBSD$ -.\" -.if t .ftr L CR diff --git a/lib/libc/rpc/PSD.doc/xdr.nts.ms b/lib/libc/rpc/PSD.doc/xdr.nts.ms deleted file mode 100644 index 260c7f3..0000000 --- a/lib/libc/rpc/PSD.doc/xdr.nts.ms +++ /dev/null @@ -1,1968 +0,0 @@ -.\" -.\" Must use -- eqn -- with this one -.\" -.\" @(#)xdr.nts.ms 2.2 88/08/05 4.0 RPCSRC -.\" $FreeBSD$ -.\" -.EQ -delim $$ -.EN -.de BT -.if \\n%=1 .tl ''- % -'' -.. -.ND -.\" prevent excess underlining in nroff -.if n .fp 2 R -.OH 'External Data Representation: Sun Technical Notes''Page %' -.EH 'Page %''External Data Representation: Sun Technical Notes' -.if \n%=1 .bp -.SH -\&External Data Representation: Sun Technical Notes -.IX XDR "Sun technical notes" -.LP -This chapter contains technical notes on Sun's implementation of the -External Data Representation (XDR) standard, a set of library routines -that allow a C programmer to describe arbitrary data structures in a -machinex-independent fashion. -For a formal specification of the XDR -standard, see the -.I "External Data Representation Standard: Protocol Specification". -XDR is the backbone of Sun's Remote Procedure Call package, in the -sense that data for remote procedure calls is transmitted using the -standard. XDR library routines should be used to transmit data -that is accessed (read or written) by more than one type of machine.\** -.FS -.IX XDR "system routines" -For a compete specification of the system External Data Representation -routines, see the -.I xdr(3N) -manual page. -.FE -.LP -This chapter contains a short tutorial overview of the XDR library -routines, a guide to accessing currently available XDR streams, and -information on defining new streams and data types. XDR was designed -to work across different languages, operating systems, and machine -architectures. Most users (particularly RPC users) will only need -the information in the -.I "Number Filters", -.I "Floating Point Filters", -and -.I "Enumeration Filters" -sections. -Programmers wishing to implement RPC and XDR on new machines -will be interested in the rest of the chapter, as well as the -.I "External Data Representaiton Standard: Protocol Specification", -which will be their primary reference. -.SH -Note: -.I -.I rpcgen -can be used to write XDR routines even in cases where no RPC calls are -being made. -.LP -On Sun systems, -C programs that want to use XDR routines -must include the file -.I <rpc/rpc.h> , -which contains all the necessary interfaces to the XDR system. -Since the C library -.I libc.a -contains all the XDR routines, -compile as normal. -.DS -example% \fBcc\0\fIprogram\fP.c\fI -.DE -.ne 3i -.NH 0 -\&Justification -.IX XDR justification -.LP -Consider the following two programs, -.I writer : -.ie t .DS -.el .DS L -.ft CW -#include <stdio.h> -.sp .5 -main() /* \fIwriter.c\fP */ -{ - long i; -.sp .5 - for (i = 0; i < 8; i++) { - if (fwrite((char *)&i, sizeof(i), 1, stdout) != 1) { - fprintf(stderr, "failed!\en"); - exit(1); - } - } - exit(0); -} -.DE -and -.I reader : -.ie t .DS -.el .DS L -.ft CW -#include <stdio.h> -.sp .5 -main() /* \fIreader.c\fP */ -{ - long i, j; -.sp .5 - for (j = 0; j < 8; j++) { - if (fread((char *)&i, sizeof (i), 1, stdin) != 1) { - fprintf(stderr, "failed!\en"); - exit(1); - } - printf("%ld ", i); - } - printf("\en"); - exit(0); -} -.DE -The two programs appear to be portable, because (a) they pass -.I lint -checking, and (b) they exhibit the same behavior when executed -on two different hardware architectures, a Sun and a VAX. -.LP -Piping the output of the -.I writer -program to the -.I reader -program gives identical results on a Sun or a VAX. -.DS -.ft CW -sun% \fBwriter | reader\fP -0 1 2 3 4 5 6 7 -sun% - - -vax% \fBwriter | reader\fP -0 1 2 3 4 5 6 7 -vax% -.DE -With the advent of local area networks and 4.2BSD came the concept -of \*Qnetwork pipes\*U \(em a process produces data on one machine, -and a second process consumes data on another machine. -A network pipe can be constructed with -.I writer -and -.I reader . -Here are the results if the first produces data on a Sun, -and the second consumes data on a VAX. -.DS -.ft CW -sun% \fBwriter | rsh vax reader\fP -0 16777216 33554432 50331648 67108864 83886080 100663296 -117440512 -sun% -.DE -Identical results can be obtained by executing -.I writer -on the VAX and -.I reader -on the Sun. These results occur because the byte ordering -of long integers differs between the VAX and the Sun, -even though word size is the same. -Note that $16777216$ is $2 sup 24$ \(em -when four bytes are reversed, the 1 winds up in the 24th bit. -.LP -Whenever data is shared by two or more machine types, there is -a need for portable data. Programs can be made data-portable by -replacing the -.I read() -and -.I write() -calls with calls to an XDR library routine -.I xdr_long() , -a filter that knows the standard representation -of a long integer in its external form. -Here are the revised versions of -.I writer : -.ie t .DS -.el .DS L -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> /* \fIxdr is a sub-library of rpc\fP */ -.sp .5 -main() /* \fIwriter.c\fP */ -{ - XDR xdrs; - long i; -.sp .5 - xdrstdio_create(&xdrs, stdout, XDR_ENCODE); - for (i = 0; i < 8; i++) { - if (!xdr_long(&xdrs, &i)) { - fprintf(stderr, "failed!\en"); - exit(1); - } - } - exit(0); -} -.DE -and -.I reader : -.ie t .DS -.el .DS L -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> /* \fIxdr is a sub-library of rpc\fP */ -.sp .5 -main() /* \fIreader.c\fP */ -{ - XDR xdrs; - long i, j; -.sp .5 - xdrstdio_create(&xdrs, stdin, XDR_DECODE); - for (j = 0; j < 8; j++) { - if (!xdr_long(&xdrs, &i)) { - fprintf(stderr, "failed!\en"); - exit(1); - } - printf("%ld ", i); - } - printf("\en"); - exit(0); -} -.DE -The new programs were executed on a Sun, -on a VAX, and from a Sun to a VAX; -the results are shown below. -.DS -.ft CW -sun% \fBwriter | reader\fP -0 1 2 3 4 5 6 7 -sun% - -vax% \fBwriter | reader\fP -0 1 2 3 4 5 6 7 -vax% - -sun% \fBwriter | rsh vax reader\fP -0 1 2 3 4 5 6 7 -sun% -.DE -.SH -Note: -.I -.IX XDR "portable data" -Integers are just the tip of the portable-data iceberg. Arbitrary -data structures present portability problems, particularly with -respect to alignment and pointers. Alignment on word boundaries -may cause the size of a structure to vary from machine to machine. -And pointers, which are very convenient to use, have no meaning -outside the machine where they are defined. -.LP -.NH 1 -\&A Canonical Standard -.IX XDR "canonical standard" -.LP -XDR's approach to standardizing data representations is -.I canonical . -That is, XDR defines a single byte order (Big Endian), a single -floating-point representation (IEEE), and so on. Any program running on -any machine can use XDR to create portable data by translating its -local representation to the XDR standard representations; similarly, any -program running on any machine can read portable data by translating the -XDR standard representaions to its local equivalents. The single standard -completely decouples programs that create or send portable data from those -that use or receive portable data. The advent of a new machine or a new -language has no effect upon the community of existing portable data creators -and users. A new machine joins this community by being \*Qtaught\*U how to -convert the standard representations and its local representations; the -local representations of other machines are irrelevant. Conversely, to -existing programs running on other machines, the local representations of -the new machine are also irrelevant; such programs can immediately read -portable data produced by the new machine because such data conforms to the -canonical standards that they already understand. -.LP -There are strong precedents for XDR's canonical approach. For example, -TCP/IP, UDP/IP, XNS, Ethernet, and, indeed, all protocols below layer five -of the ISO model, are canonical protocols. The advantage of any canonical -approach is simplicity; in the case of XDR, a single set of conversion -routines is written once and is never touched again. The canonical approach -has a disadvantage, but it is unimportant in real-world data transfer -applications. Suppose two Little-Endian machines are transferring integers -according to the XDR standard. The sending machine converts the integers -from Little-Endian byte order to XDR (Big-Endian) byte order; the receiving -machine performs the reverse conversion. Because both machines observe the -same byte order, their conversions are unnecessary. The point, however, is -not necessity, but cost as compared to the alternative. -.LP -The time spent converting to and from a canonical representation is -insignificant, especially in networking applications. Most of the time -required to prepare a data structure for transfer is not spent in conversion -but in traversing the elements of the data structure. To transmit a tree, -for example, each leaf must be visited and each element in a leaf record must -be copied to a buffer and aligned there; storage for the leaf may have to be -deallocated as well. Similarly, to receive a tree, storage must be -allocated for each leaf, data must be moved from the buffer to the leaf and -properly aligned, and pointers must be constructed to link the leaves -together. Every machine pays the cost of traversing and copying data -structures whether or not conversion is required. In networking -applications, communications overhead\(emthe time required to move the data -down through the sender's protocol layers, across the network and up through -the receiver's protocol layers\(emdwarfs conversion overhead. -.NH 1 -\&The XDR Library -.IX "XDR" "library" -.LP -The XDR library not only solves data portability problems, it also -allows you to write and read arbitrary C constructs in a consistent, -specified, well-documented manner. Thus, it can make sense to use the -library even when the data is not shared among machines on a network. -.LP -The XDR library has filter routines for -strings (null-terminated arrays of bytes), -structures, unions, and arrays, to name a few. -Using more primitive routines, -you can write your own specific XDR routines -to describe arbitrary data structures, -including elements of arrays, arms of unions, -or objects pointed at from other structures. -The structures themselves may contain arrays of arbitrary elements, -or pointers to other structures. -.LP -Let's examine the two programs more closely. -There is a family of XDR stream creation routines -in which each member treats the stream of bits differently. -In our example, data is manipulated using standard I/O routines, -so we use -.I xdrstdio_create (). -.IX xdrstdio_create() "" "\fIxdrstdio_create()\fP" -The parameters to XDR stream creation routines -vary according to their function. -In our example, -.I xdrstdio_create() -takes a pointer to an XDR structure that it initializes, -a pointer to a -.I FILE -that the input or output is performed on, and the operation. -The operation may be -.I XDR_ENCODE -for serializing in the -.I writer -program, or -.I XDR_DECODE -for deserializing in the -.I reader -program. -.LP -Note: RPC users never need to create XDR streams; -the RPC system itself creates these streams, -which are then passed to the users. -.LP -The -.I xdr_long() -.IX xdr_long() "" "\fIxdr_long()\fP" -primitive is characteristic of most XDR library -primitives and all client XDR routines. -First, the routine returns -.I FALSE -(0) if it fails, and -.I TRUE -(1) if it succeeds. -Second, for each data type, -.I xxx , -there is an associated XDR routine of the form: -.DS -.ft CW -xdr_xxx(xdrs, xp) - XDR *xdrs; - xxx *xp; -{ -} -.DE -In our case, -.I xxx -is long, and the corresponding XDR routine is -a primitive, -.I xdr_long() . -The client could also define an arbitrary structure -.I xxx -in which case the client would also supply the routine -.I xdr_xxx (), -describing each field by calling XDR routines -of the appropriate type. -In all cases the first parameter, -.I xdrs -can be treated as an opaque handle, -and passed to the primitive routines. -.LP -XDR routines are direction independent; -that is, the same routines are called to serialize or deserialize data. -This feature is critical to software engineering of portable data. -The idea is to call the same routine for either operation \(em -this almost guarantees that serialized data can also be deserialized. -One routine is used by both producer and consumer of networked data. -This is implemented by always passing the address -of an object rather than the object itself \(em -only in the case of deserialization is the object modified. -This feature is not shown in our trivial example, -but its value becomes obvious when nontrivial data structures -are passed among machines. -If needed, the user can obtain the -direction of the XDR operation. -See the -.I "XDR Operation Directions" -section below for details. -.LP -Let's look at a slightly more complicated example. -Assume that a person's gross assets and liabilities -are to be exchanged among processes. -Also assume that these values are important enough -to warrant their own data type: -.ie t .DS -.el .DS L -.ft CW -struct gnumbers { - long g_assets; - long g_liabilities; -}; -.DE -The corresponding XDR routine describing this structure would be: -.ie t .DS -.el .DS L -.ft CW -bool_t /* \fITRUE is success, FALSE is failure\fP */ -xdr_gnumbers(xdrs, gp) - XDR *xdrs; - struct gnumbers *gp; -{ - if (xdr_long(xdrs, &gp->g_assets) && - xdr_long(xdrs, &gp->g_liabilities)) - return(TRUE); - return(FALSE); -} -.DE -Note that the parameter -.I xdrs -is never inspected or modified; -it is only passed on to the subcomponent routines. -It is imperative to inspect the return value of each XDR routine call, -and to give up immediately and return -.I FALSE -if the subroutine fails. -.LP -This example also shows that the type -.I bool_t -is declared as an integer whose only values are -.I TRUE -(1) and -.I FALSE -(0). This document uses the following definitions: -.ie t .DS -.el .DS L -.ft CW -#define bool_t int -#define TRUE 1 -#define FALSE 0 -.DE -.LP -Keeping these conventions in mind, -.I xdr_gnumbers() -can be rewritten as follows: -.ie t .DS -.el .DS L -.ft CW -xdr_gnumbers(xdrs, gp) - XDR *xdrs; - struct gnumbers *gp; -{ - return(xdr_long(xdrs, &gp->g_assets) && - xdr_long(xdrs, &gp->g_liabilities)); -} -.DE -This document uses both coding styles. -.NH 1 -\&XDR Library Primitives -.IX "library primitives for XDR" -.IX XDR "library primitives" -.LP -This section gives a synopsis of each XDR primitive. -It starts with basic data types and moves on to constructed data types. -Finally, XDR utilities are discussed. -The interface to these primitives -and utilities is defined in the include file -.I <rpc/xdr.h> , -automatically included by -.I <rpc/rpc.h> . -.NH 2 -\&Number Filters -.IX "XDR library" "number filters" -.LP -The XDR library provides primitives to translate between numbers -and their corresponding external representations. -Primitives cover the set of numbers in: -.DS -.ft CW -[signed, unsigned] * [short, int, long] -.DE -.ne 2i -Specifically, the eight primitives are: -.DS -.ft CW -bool_t xdr_char(xdrs, cp) - XDR *xdrs; - char *cp; -.sp .5 -bool_t xdr_u_char(xdrs, ucp) - XDR *xdrs; - unsigned char *ucp; -.sp .5 -bool_t xdr_int(xdrs, ip) - XDR *xdrs; - int *ip; -.sp .5 -bool_t xdr_u_int(xdrs, up) - XDR *xdrs; - unsigned *up; -.sp .5 -bool_t xdr_long(xdrs, lip) - XDR *xdrs; - long *lip; -.sp .5 -bool_t xdr_u_long(xdrs, lup) - XDR *xdrs; - u_long *lup; -.sp .5 -bool_t xdr_short(xdrs, sip) - XDR *xdrs; - short *sip; -.sp .5 -bool_t xdr_u_short(xdrs, sup) - XDR *xdrs; - u_short *sup; -.DE -The first parameter, -.I xdrs , -is an XDR stream handle. -The second parameter is the address of the number -that provides data to the stream or receives data from it. -All routines return -.I TRUE -if they complete successfully, and -.I FALSE -otherwise. -.NH 2 -\&Floating Point Filters -.IX "XDR library" "floating point filters" -.LP -The XDR library also provides primitive routines -for C's floating point types: -.DS -.ft CW -bool_t xdr_float(xdrs, fp) - XDR *xdrs; - float *fp; -.sp .5 -bool_t xdr_double(xdrs, dp) - XDR *xdrs; - double *dp; -.DE -The first parameter, -.I xdrs -is an XDR stream handle. -The second parameter is the address -of the floating point number that provides data to the stream -or receives data from it. -Both routines return -.I TRUE -if they complete successfully, and -.I FALSE -otherwise. -.LP -Note: Since the numbers are represented in IEEE floating point, -routines may fail when decoding a valid IEEE representation -into a machine-specific representation, or vice-versa. -.NH 2 -\&Enumeration Filters -.IX "XDR library" "enumeration filters" -.LP -The XDR library provides a primitive for generic enumerations. -The primitive assumes that a C -.I enum -has the same representation inside the machine as a C integer. -The boolean type is an important instance of the -.I enum . -The external representation of a boolean is always -.I TRUE -(1) or -.I FALSE -(0). -.DS -.ft CW -#define bool_t int -#define FALSE 0 -#define TRUE 1 -.sp .5 -#define enum_t int -.sp .5 -bool_t xdr_enum(xdrs, ep) - XDR *xdrs; - enum_t *ep; -.sp .5 -bool_t xdr_bool(xdrs, bp) - XDR *xdrs; - bool_t *bp; -.DE -The second parameters -.I ep -and -.I bp -are addresses of the associated type that provides data to, or -receives data from, the stream -.I xdrs . -.NH 2 -\&No Data -.IX "XDR library" "no data" -.LP -Occasionally, an XDR routine must be supplied to the RPC system, -even when no data is passed or required. -The library provides such a routine: -.DS -.ft CW -bool_t xdr_void(); /* \fIalways returns TRUE\fP */ -.DE -.NH 2 -\&Constructed Data Type Filters -.IX "XDR library" "constructed data type filters" -.LP -Constructed or compound data type primitives -require more parameters and perform more complicated functions -then the primitives discussed above. -This section includes primitives for -strings, arrays, unions, and pointers to structures. -.LP -Constructed data type primitives may use memory management. -In many cases, memory is allocated when deserializing data with -.I XDR_DECODE -Therefore, the XDR package must provide means to deallocate memory. -This is done by an XDR operation, -.I XDR_FREE -To review, the three XDR directional operations are -.I XDR_ENCODE , -.I XDR_DECODE -and -.I XDR_FREE . -.NH 3 -\&Strings -.IX "XDR library" "strings" -.LP -In C, a string is defined as a sequence of bytes -terminated by a null byte, -which is not considered when calculating string length. -However, when a string is passed or manipulated, -a pointer to it is employed. -Therefore, the XDR library defines a string to be a -.I "char *" -and not a sequence of characters. -The external representation of a string is drastically different -from its internal representation. -Externally, strings are represented as -sequences of ASCII characters, -while internally, they are represented with character pointers. -Conversion between the two representations -is accomplished with the routine -.I xdr_string (): -.IX xdr_string() "" \fIxdr_string()\fP -.DS -.ft CW -bool_t xdr_string(xdrs, sp, maxlength) - XDR *xdrs; - char **sp; - u_int maxlength; -.DE -The first parameter -.I xdrs -is the XDR stream handle. -The second parameter -.I sp -is a pointer to a string (type -.I "char **" . -The third parameter -.I maxlength -specifies the maximum number of bytes allowed during encoding or decoding. -its value is usually specified by a protocol. For example, a protocol -specification may say that a file name may be no longer than 255 characters. -.LP -The routine returns -.I FALSE -if the number of characters exceeds -.I maxlength , -and -.I TRUE -if it doesn't. -.SH -Keep -.I maxlength -small. If it is too big you can blow the heap, since -.I xdr_string() -will call -.I malloc() -for space. -.LP -The behavior of -.I xdr_string() -.IX xdr_string() "" \fIxdr_string()\fP -is similar to the behavior of other routines -discussed in this section. The direction -.I XDR_ENCODE -is easiest to understand. The parameter -.I sp -points to a string of a certain length; -if the string does not exceed -.I maxlength , -the bytes are serialized. -.LP -The effect of deserializing a string is subtle. -First the length of the incoming string is determined; -it must not exceed -.I maxlength . -Next -.I sp -is dereferenced; if the the value is -.I NULL , -then a string of the appropriate length is allocated and -.I *sp -is set to this string. -If the original value of -.I *sp -is non-null, then the XDR package assumes -that a target area has been allocated, -which can hold strings no longer than -.I maxlength . -In either case, the string is decoded into the target area. -The routine then appends a null character to the string. -.LP -In the -.I XDR_FREE -operation, the string is obtained by dereferencing -.I sp . -If the string is not -.I NULL , -it is freed and -.I *sp -is set to -.I NULL . -In this operation, -.I xdr_string() -ignores the -.I maxlength -parameter. -.NH 3 -\&Byte Arrays -.IX "XDR library" "byte arrays" -.LP -Often variable-length arrays of bytes are preferable to strings. -Byte arrays differ from strings in the following three ways: -1) the length of the array (the byte count) is explicitly -located in an unsigned integer, -2) the byte sequence is not terminated by a null character, and -3) the external representation of the bytes is the same as their -internal representation. -The primitive -.I xdr_bytes() -.IX xdr_bytes() "" \fIxdr_bytes()\fP -converts between the internal and external -representations of byte arrays: -.DS -.ft CW -bool_t xdr_bytes(xdrs, bpp, lp, maxlength) - XDR *xdrs; - char **bpp; - u_int *lp; - u_int maxlength; -.DE -The usage of the first, second and fourth parameters -are identical to the first, second and third parameters of -.I xdr_string (), -respectively. -The length of the byte area is obtained by dereferencing -.I lp -when serializing; -.I *lp -is set to the byte length when deserializing. -.NH 3 -\&Arrays -.IX "XDR library" "arrays" -.LP -The XDR library package provides a primitive -for handling arrays of arbitrary elements. -The -.I xdr_bytes() -routine treats a subset of generic arrays, -in which the size of array elements is known to be 1, -and the external description of each element is built-in. -The generic array primitive, -.I xdr_array() , -.IX xdr_array() "" \fIxdr_array()\fP -requires parameters identical to those of -.I xdr_bytes() -plus two more: -the size of array elements, -and an XDR routine to handle each of the elements. -This routine is called to encode or decode -each element of the array. -.DS -.ft CW -bool_t -xdr_array(xdrs, ap, lp, maxlength, elementsiz, xdr_element) - XDR *xdrs; - char **ap; - u_int *lp; - u_int maxlength; - u_int elementsiz; - bool_t (*xdr_element)(); -.DE -The parameter -.I ap -is the address of the pointer to the array. -If -.I *ap -is -.I NULL -when the array is being deserialized, -XDR allocates an array of the appropriate size and sets -.I *ap -to that array. -The element count of the array is obtained from -.I *lp -when the array is serialized; -.I *lp -is set to the array length when the array is deserialized. -The parameter -.I maxlength -is the maximum number of elements that the array is allowed to have; -.I elementsiz -is the byte size of each element of the array -(the C function -.I sizeof() -can be used to obtain this value). -The -.I xdr_element() -.IX xdr_element() "" \fIxdr_element()\fP -routine is called to serialize, deserialize, or free -each element of the array. -.br -.LP -Before defining more constructed data types, it is appropriate to -present three examples. -.LP -.I "Example A:" -.br -A user on a networked machine can be identified by -(a) the machine name, such as -.I krypton : -see the -.I gethostname -man page; (b) the user's UID: see the -.I geteuid -man page; and (c) the group numbers to which the user belongs: -see the -.I getgroups -man page. A structure with this information and its associated -XDR routine could be coded like this: -.ie t .DS -.el .DS L -.ft CW -struct netuser { - char *nu_machinename; - int nu_uid; - u_int nu_glen; - int *nu_gids; -}; -#define NLEN 255 /* \fImachine names < 256 chars\fP */ -#define NGRPS 20 /* \fIuser can't be in > 20 groups\fP */ -.sp .5 -bool_t -xdr_netuser(xdrs, nup) - XDR *xdrs; - struct netuser *nup; -{ - return(xdr_string(xdrs, &nup->nu_machinename, NLEN) && - xdr_int(xdrs, &nup->nu_uid) && - xdr_array(xdrs, &nup->nu_gids, &nup->nu_glen, - NGRPS, sizeof (int), xdr_int)); -} -.DE -.LP -.I "Example B:" -.br -A party of network users could be implemented -as an array of -.I netuser -structure. -The declaration and its associated XDR routines -are as follows: -.ie t .DS -.el .DS L -.ft CW -struct party { - u_int p_len; - struct netuser *p_nusers; -}; -#define PLEN 500 /* \fImax number of users in a party\fP */ -.sp .5 -bool_t -xdr_party(xdrs, pp) - XDR *xdrs; - struct party *pp; -{ - return(xdr_array(xdrs, &pp->p_nusers, &pp->p_len, PLEN, - sizeof (struct netuser), xdr_netuser)); -} -.DE -.LP -.I "Example C:" -.br -The well-known parameters to -.I main , -.I argc -and -.I argv -can be combined into a structure. -An array of these structures can make up a history of commands. -The declarations and XDR routines might look like: -.ie t .DS -.el .DS L -.ft CW -struct cmd { - u_int c_argc; - char **c_argv; -}; -#define ALEN 1000 /* \fIargs cannot be > 1000 chars\fP */ -#define NARGC 100 /* \fIcommands cannot have > 100 args\fP */ - -struct history { - u_int h_len; - struct cmd *h_cmds; -}; -#define NCMDS 75 /* \fIhistory is no more than 75 commands\fP */ - -bool_t -xdr_wrap_string(xdrs, sp) - XDR *xdrs; - char **sp; -{ - return(xdr_string(xdrs, sp, ALEN)); -} -.DE -.ie t .DS -.el .DS L -.ft CW -bool_t -xdr_cmd(xdrs, cp) - XDR *xdrs; - struct cmd *cp; -{ - return(xdr_array(xdrs, &cp->c_argv, &cp->c_argc, NARGC, - sizeof (char *), xdr_wrap_string)); -} -.DE -.ie t .DS -.el .DS L -.ft CW -bool_t -xdr_history(xdrs, hp) - XDR *xdrs; - struct history *hp; -{ - return(xdr_array(xdrs, &hp->h_cmds, &hp->h_len, NCMDS, - sizeof (struct cmd), xdr_cmd)); -} -.DE -The most confusing part of this example is that the routine -.I xdr_wrap_string() -is needed to package the -.I xdr_string() -routine, because the implementation of -.I xdr_array() -only passes two parameters to the array element description routine; -.I xdr_wrap_string() -supplies the third parameter to -.I xdr_string (). -.LP -By now the recursive nature of the XDR library should be obvious. -Let's continue with more constructed data types. -.NH 3 -\&Opaque Data -.IX "XDR library" "opaque data" -.LP -In some protocols, handles are passed from a server to client. -The client passes the handle back to the server at some later time. -Handles are never inspected by clients; -they are obtained and submitted. -That is to say, handles are opaque. -The -.I xdr_opaque() -.IX xdr_opaque() "" \fIxdr_opaque()\fP -primitive is used for describing fixed sized, opaque bytes. -.DS -.ft CW -bool_t xdr_opaque(xdrs, p, len) - XDR *xdrs; - char *p; - u_int len; -.DE -The parameter -.I p -is the location of the bytes; -.I len -is the number of bytes in the opaque object. -By definition, the actual data -contained in the opaque object are not machine portable. -.NH 3 -\&Fixed Sized Arrays -.IX "XDR library" "fixed sized arrays" -.LP -The XDR library provides a primitive, -.I xdr_vector (), -for fixed-length arrays. -.ie t .DS -.el .DS L -.ft CW -#define NLEN 255 /* \fImachine names must be < 256 chars\fP */ -#define NGRPS 20 /* \fIuser belongs to exactly 20 groups\fP */ -.sp .5 -struct netuser { - char *nu_machinename; - int nu_uid; - int nu_gids[NGRPS]; -}; -.sp .5 -bool_t -xdr_netuser(xdrs, nup) - XDR *xdrs; - struct netuser *nup; -{ - int i; -.sp .5 - if (!xdr_string(xdrs, &nup->nu_machinename, NLEN)) - return(FALSE); - if (!xdr_int(xdrs, &nup->nu_uid)) - return(FALSE); - if (!xdr_vector(xdrs, nup->nu_gids, NGRPS, sizeof(int), - xdr_int)) { - return(FALSE); - } - return(TRUE); -} -.DE -.NH 3 -\&Discriminated Unions -.IX "XDR library" "discriminated unions" -.LP -The XDR library supports discriminated unions. -A discriminated union is a C union and an -.I enum_t -value that selects an \*Qarm\*U of the union. -.DS -.ft CW -struct xdr_discrim { - enum_t value; - bool_t (*proc)(); -}; -.sp .5 -bool_t xdr_union(xdrs, dscmp, unp, arms, defaultarm) - XDR *xdrs; - enum_t *dscmp; - char *unp; - struct xdr_discrim *arms; - bool_t (*defaultarm)(); /* \fImay equal NULL\fP */ -.DE -First the routine translates the discriminant of the union located at -.I *dscmp . -The discriminant is always an -.I enum_t . -Next the union located at -.I *unp -is translated. -The parameter -.I arms -is a pointer to an array of -.I xdr_discrim -structures. -Each structure contains an ordered pair of -.I [value,proc] . -If the union's discriminant is equal to the associated -.I value , -then the -.I proc -is called to translate the union. -The end of the -.I xdr_discrim -structure array is denoted by a routine of value -.I NULL -(0). If the discriminant is not found in the -.I arms -array, then the -.I defaultarm -procedure is called if it is non-null; -otherwise the routine returns -.I FALSE . -.LP -.I "Example D:" -Suppose the type of a union may be integer, -character pointer (a string), or a -.I gnumbers -structure. -Also, assume the union and its current type -are declared in a structure. -The declaration is: -.ie t .DS -.el .DS L -.ft CW -enum utype { INTEGER=1, STRING=2, GNUMBERS=3 }; -.sp .5 -struct u_tag { - enum utype utype; /* \fIthe union's discriminant\fP */ - union { - int ival; - char *pval; - struct gnumbers gn; - } uval; -}; -.DE -The following constructs and XDR procedure (de)serialize -the discriminated union: -.ie t .DS -.el .DS L -.ft CW -struct xdr_discrim u_tag_arms[4] = { - { INTEGER, xdr_int }, - { GNUMBERS, xdr_gnumbers } - { STRING, xdr_wrap_string }, - { __dontcare__, NULL } - /* \fIalways terminate arms with a NULL xdr_proc\fP */ -} -.sp .5 -bool_t -xdr_u_tag(xdrs, utp) - XDR *xdrs; - struct u_tag *utp; -{ - return(xdr_union(xdrs, &utp->utype, &utp->uval, - u_tag_arms, NULL)); -} -.DE -The routine -.I xdr_gnumbers() -was presented above in -.I "The XDR Library" -section. -.I xdr_wrap_string() -was presented in example C. -The default -.I arm -parameter to -.I xdr_union() -(the last parameter) is -.I NULL -in this example. Therefore the value of the union's discriminant -may legally take on only values listed in the -.I u_tag_arms -array. This example also demonstrates that -the elements of the arm's array do not need to be sorted. -.LP -It is worth pointing out that the values of the discriminant -may be sparse, though in this example they are not. -It is always good -practice to assign explicitly integer values to each element of the -discriminant's type. -This practice both documents the external -representation of the discriminant and guarantees that different -C compilers emit identical discriminant values. -.LP -Exercise: Implement -.I xdr_union() -using the other primitives in this section. -.NH 3 -\&Pointers -.IX "XDR library" "pointers" -.LP -In C it is often convenient to put pointers -to another structure within a structure. -The -.I xdr_reference() -.IX xdr_reference() "" \fIxdr_reference()\fP -primitive makes it easy to serialize, deserialize, and free -these referenced structures. -.DS -.ft CW -bool_t xdr_reference(xdrs, pp, size, proc) - XDR *xdrs; - char **pp; - u_int ssize; - bool_t (*proc)(); -.DE -.LP -Parameter -.I pp -is the address of -the pointer to the structure; -parameter -.I ssize -is the size in bytes of the structure (use the C function -.I sizeof() -to obtain this value); and -.I proc -is the XDR routine that describes the structure. -When decoding data, storage is allocated if -.I *pp -is -.I NULL . -.LP -There is no need for a primitive -.I xdr_struct() -to describe structures within structures, -because pointers are always sufficient. -.LP -Exercise: Implement -.I xdr_reference() -using -.I xdr_array (). -Warning: -.I xdr_reference() -and -.I xdr_array() -are NOT interchangeable external representations of data. -.LP -.I "Example E:" -Suppose there is a structure containing a person's name -and a pointer to a -.I gnumbers -structure containing the person's gross assets and liabilities. -The construct is: -.DS -.ft CW -struct pgn { - char *name; - struct gnumbers *gnp; -}; -.DE -The corresponding XDR routine for this structure is: -.DS -.ft CW -bool_t -xdr_pgn(xdrs, pp) - XDR *xdrs; - struct pgn *pp; -{ - if (xdr_string(xdrs, &pp->name, NLEN) && - xdr_reference(xdrs, &pp->gnp, - sizeof(struct gnumbers), xdr_gnumbers)) - return(TRUE); - return(FALSE); -} -.DE -.IX "pointer semantics and XDR" -.I "Pointer Semantics and XDR" -.LP -In many applications, C programmers attach double meaning to -the values of a pointer. Typically the value -.I NULL -(or zero) means data is not needed, -yet some application-specific interpretation applies. -In essence, the C programmer is encoding -a discriminated union efficiently -by overloading the interpretation of the value of a pointer. -For instance, in example E a -.I NULL -pointer value for -.I gnp -could indicate that -the person's assets and liabilities are unknown. -That is, the pointer value encodes two things: -whether or not the data is known; -and if it is known, where it is located in memory. -Linked lists are an extreme example of the use -of application-specific pointer interpretation. -.LP -The primitive -.I xdr_reference() -.IX xdr_reference() "" \fIxdr_reference()\fP -cannot and does not attach any special -meaning to a null-value pointer during serialization. -That is, passing an address of a pointer whose value is -.I NULL -to -.I xdr_reference() -when serialing data will most likely cause a memory fault and, on the UNIX -system, a core dump. -.LP -.I xdr_pointer() -correctly handles -.I NULL -pointers. For more information about its use, see -the -.I "Linked Lists" -topics below. -.LP -.I Exercise: -After reading the section on -.I "Linked Lists" , -return here and extend example E so that -it can correctly deal with -.I NULL -pointer values. -.LP -.I Exercise: -Using the -.I xdr_union (), -.I xdr_reference() -and -.I xdr_void() -primitives, implement a generic pointer handling primitive -that implicitly deals with -.I NULL -pointers. That is, implement -.I xdr_pointer (). -.NH 2 -\&Non-filter Primitives -.IX "XDR" "non-filter primitives" -.LP -XDR streams can be manipulated with -the primitives discussed in this section. -.DS -.ft CW -u_int xdr_getpos(xdrs) - XDR *xdrs; -.sp .5 -bool_t xdr_setpos(xdrs, pos) - XDR *xdrs; - u_int pos; -.sp .5 -xdr_destroy(xdrs) - XDR *xdrs; -.DE -The routine -.I xdr_getpos() -.IX xdr_getpos() "" \fIxdr_getpos()\fP -returns an unsigned integer -that describes the current position in the data stream. -Warning: In some XDR streams, the returned value of -.I xdr_getpos() -is meaningless; -the routine returns a \-1 in this case -(though \-1 should be a legitimate value). -.LP -The routine -.I xdr_setpos() -.IX xdr_setpos() "" \fIxdr_setpos()\fP -sets a stream position to -.I pos . -Warning: In some XDR streams, setting a position is impossible; -in such cases, -.I xdr_setpos() -will return -.I FALSE . -This routine will also fail if the requested position is out-of-bounds. -The definition of bounds varies from stream to stream. -.LP -The -.I xdr_destroy() -.IX xdr_destroy() "" \fIxdr_destroy()\fP -primitive destroys the XDR stream. -Usage of the stream -after calling this routine is undefined. -.NH 2 -\&XDR Operation Directions -.IX XDR "operation directions" -.IX "direction of XDR operations" -.LP -At times you may wish to optimize XDR routines by taking -advantage of the direction of the operation \(em -.I XDR_ENCODE -.I XDR_DECODE -or -.I XDR_FREE -The value -.I xdrs->x_op -always contains the direction of the XDR operation. -Programmers are not encouraged to take advantage of this information. -Therefore, no example is presented here. However, an example in the -.I "Linked Lists" -topic below, demonstrates the usefulness of the -.I xdrs->x_op -field. -.NH 2 -\&XDR Stream Access -.IX "XDR" "stream access" -.LP -An XDR stream is obtained by calling the appropriate creation routine. -These creation routines take arguments that are tailored to the -specific properties of the stream. -.LP -Streams currently exist for (de)serialization of data to or from -standard I/O -.I FILE -streams, TCP/IP connections and UNIX files, and memory. -.NH 3 -\&Standard I/O Streams -.IX "XDR" "standard I/O streams" -.LP -XDR streams can be interfaced to standard I/O using the -.I xdrstdio_create() -.IX xdrstdio_create() "" \fIxdrstdio_create()\fP -routine as follows: -.DS -.ft CW -#include <stdio.h> -#include <rpc/rpc.h> /* \fIxdr streams part of rpc\fP */ -.sp .5 -void -xdrstdio_create(xdrs, fp, x_op) - XDR *xdrs; - FILE *fp; - enum xdr_op x_op; -.DE -The routine -.I xdrstdio_create() -initializes an XDR stream pointed to by -.I xdrs . -The XDR stream interfaces to the standard I/O library. -Parameter -.I fp -is an open file, and -.I x_op -is an XDR direction. -.NH 3 -\&Memory Streams -.IX "XDR" "memory streams" -.LP -Memory streams allow the streaming of data into or out of -a specified area of memory: -.DS -.ft CW -#include <rpc/rpc.h> -.sp .5 -void -xdrmem_create(xdrs, addr, len, x_op) - XDR *xdrs; - char *addr; - u_int len; - enum xdr_op x_op; -.DE -The routine -.I xdrmem_create() -.IX xdrmem_create() "" \fIxdrmem_create()\fP -initializes an XDR stream in local memory. -The memory is pointed to by parameter -.I addr ; -parameter -.I len -is the length in bytes of the memory. -The parameters -.I xdrs -and -.I x_op -are identical to the corresponding parameters of -.I xdrstdio_create (). -Currently, the UDP/IP implementation of RPC uses -.I xdrmem_create (). -Complete call or result messages are built in memory before calling the -.I sendto() -system routine. -.NH 3 -\&Record (TCP/IP) Streams -.IX "XDR" "record (TCP/IP) streams" -.LP -A record stream is an XDR stream built on top of -a record marking standard that is built on top of the -UNIX file or 4.2 BSD connection interface. -.DS -.ft CW -#include <rpc/rpc.h> /* \fIxdr streams part of rpc\fP */ -.sp .5 -xdrrec_create(xdrs, - sendsize, recvsize, iohandle, readproc, writeproc) - XDR *xdrs; - u_int sendsize, recvsize; - char *iohandle; - int (*readproc)(), (*writeproc)(); -.DE -The routine -.I xdrrec_create() -provides an XDR stream interface that allows for a bidirectional, -arbitrarily long sequence of records. -The contents of the records are meant to be data in XDR form. -The stream's primary use is for interfacing RPC to TCP connections. -However, it can be used to stream data into or out of normal -UNIX files. -.LP -The parameter -.I xdrs -is similar to the corresponding parameter described above. -The stream does its own data buffering similar to that of standard I/O. -The parameters -.I sendsize -and -.I recvsize -determine the size in bytes of the output and input buffers, respectively; -if their values are zero (0), then predetermined defaults are used. -When a buffer needs to be filled or flushed, the routine -.I readproc() -or -.I writeproc() -is called, respectively. -The usage and behavior of these -routines are similar to the UNIX system calls -.I read() -and -.I write (). -However, -the first parameter to each of these routines is the opaque parameter -.I iohandle . -The other two parameters -.I buf "" -and -.I nbytes ) -and the results -(byte count) are identical to the system routines. -If -.I xxx -is -.I readproc() -or -.I writeproc (), -then it has the following form: -.DS -.ft CW -.ft I -/* - * returns the actual number of bytes transferred. - * -1 is an error - */ -.ft CW -int -xxx(iohandle, buf, len) - char *iohandle; - char *buf; - int nbytes; -.DE -The XDR stream provides means for delimiting records in the byte stream. -The implementation details of delimiting records in a stream are -discussed in the -.I "Advanced Topics" -topic below. -The primitives that are specific to record streams are as follows: -.DS -.ft CW -bool_t -xdrrec_endofrecord(xdrs, flushnow) - XDR *xdrs; - bool_t flushnow; -.sp .5 -bool_t -xdrrec_skiprecord(xdrs) - XDR *xdrs; -.sp .5 -bool_t -xdrrec_eof(xdrs) - XDR *xdrs; -.DE -The routine -.I xdrrec_endofrecord() -.IX xdrrec_endofrecord() "" \fIxdrrec_endofrecord()\fP -causes the current outgoing data to be marked as a record. -If the parameter -.I flushnow -is -.I TRUE , -then the stream's -.I writeproc -will be called; otherwise, -.I writeproc -will be called when the output buffer has been filled. -.LP -The routine -.I xdrrec_skiprecord() -.IX xdrrec_skiprecord() "" \fIxdrrec_skiprecord()\fP -causes an input stream's position to be moved past -the current record boundary and onto the -beginning of the next record in the stream. -.LP -If there is no more data in the stream's input buffer, -then the routine -.I xdrrec_eof() -.IX xdrrec_eof() "" \fIxdrrec_eof()\fP -returns -.I TRUE . -That is not to say that there is no more data -in the underlying file descriptor. -.NH 2 -\&XDR Stream Implementation -.IX "XDR" "stream implementation" -.IX "stream implementation in XDR" -.LP -This section provides the abstract data types needed -to implement new instances of XDR streams. -.NH 3 -\&The XDR Object -.IX "XDR" "object" -.LP -The following structure defines the interface to an XDR stream: -.ie t .DS -.el .DS L -.ft CW -enum xdr_op { XDR_ENCODE=0, XDR_DECODE=1, XDR_FREE=2 }; -.sp .5 -typedef struct { - enum xdr_op x_op; /* \fIoperation; fast added param\fP */ - struct xdr_ops { - bool_t (*x_getlong)(); /* \fIget long from stream\fP */ - bool_t (*x_putlong)(); /* \fIput long to stream\fP */ - bool_t (*x_getbytes)(); /* \fIget bytes from stream\fP */ - bool_t (*x_putbytes)(); /* \fIput bytes to stream\fP */ - u_int (*x_getpostn)(); /* \fIreturn stream offset\fP */ - bool_t (*x_setpostn)(); /* \fIreposition offset\fP */ - caddr_t (*x_inline)(); /* \fIptr to buffered data\fP */ - VOID (*x_destroy)(); /* \fIfree private area\fP */ - } *x_ops; - caddr_t x_public; /* \fIusers' data\fP */ - caddr_t x_private; /* \fIpointer to private data\fP */ - caddr_t x_base; /* \fIprivate for position info\fP */ - int x_handy; /* \fIextra private word\fP */ -} XDR; -.DE -The -.I x_op -field is the current operation being performed on the stream. -This field is important to the XDR primitives, -but should not affect a stream's implementation. -That is, a stream's implementation should not depend -on this value. -The fields -.I x_private , -.I x_base , -and -.I x_handy -are private to the particular -stream's implementation. -The field -.I x_public -is for the XDR client and should never be used by -the XDR stream implementations or the XDR primitives. -.I x_getpostn() , -.I x_setpostn() -and -.I x_destroy() -are macros for accessing operations. The operation -.I x_inline() -takes two parameters: -an XDR *, and an unsigned integer, which is a byte count. -The routine returns a pointer to a piece of -the stream's internal buffer. -The caller can then use the buffer segment for any purpose. -From the stream's point of view, the bytes in the -buffer segment have been consumed or put. -The routine may return -.I NULL -if it cannot return a buffer segment of the requested size. -(The -.I x_inline() -routine is for cycle squeezers. -Use of the resulting buffer is not data-portable. -Users are encouraged not to use this feature.) -.LP -The operations -.I x_getbytes() -and -.I x_putbytes() -blindly get and put sequences of bytes -from or to the underlying stream; -they return -.I TRUE -if they are successful, and -.I FALSE -otherwise. The routines have identical parameters (replace -.I xxx ): -.DS -.ft CW -bool_t -xxxbytes(xdrs, buf, bytecount) - XDR *xdrs; - char *buf; - u_int bytecount; -.DE -The operations -.I x_getlong() -and -.I x_putlong() -receive and put -long numbers from and to the data stream. -It is the responsibility of these routines -to translate the numbers between the machine representation -and the (standard) external representation. -The UNIX primitives -.I htonl() -and -.I ntohl() -can be helpful in accomplishing this. -The higher-level XDR implementation assumes that -signed and unsigned long integers contain the same number of bits, -and that nonnegative integers -have the same bit representations as unsigned integers. -The routines return -.I TRUE -if they succeed, and -.I FALSE -otherwise. They have identical parameters: -.DS -.ft CW -bool_t -xxxlong(xdrs, lp) - XDR *xdrs; - long *lp; -.DE -Implementors of new XDR streams must make an XDR structure -(with new operation routines) available to clients, -using some kind of create routine. -.NH 1 -\&Advanced Topics -.IX XDR "advanced topics" -.LP -This section describes techniques for passing data structures that -are not covered in the preceding sections. Such structures include -linked lists (of arbitrary lengths). Unlike the simpler examples -covered in the earlier sections, the following examples are written -using both the XDR C library routines and the XDR data description -language. -The -.I "External Data Representation Standard: Protocol Specification" -describes this -language in complete detail. -.NH 2 -\&Linked Lists -.IX XDR "linked lists" -.LP -The last example in the -.I Pointers -topic earlier in this chapter -presented a C data structure and its associated XDR -routines for an individual's gross assets and liabilities. -The example is duplicated below: -.ie t .DS -.el .DS L -.ft CW -struct gnumbers { - long g_assets; - long g_liabilities; -}; -.sp .5 -bool_t -xdr_gnumbers(xdrs, gp) - XDR *xdrs; - struct gnumbers *gp; -{ - if (xdr_long(xdrs, &(gp->g_assets))) - return(xdr_long(xdrs, &(gp->g_liabilities))); - return(FALSE); -} -.DE -.LP -Now assume that we wish to implement a linked list of such information. -A data structure could be constructed as follows: -.ie t .DS -.el .DS L -.ft CW -struct gnumbers_node { - struct gnumbers gn_numbers; - struct gnumbers_node *gn_next; -}; -.sp .5 -typedef struct gnumbers_node *gnumbers_list; -.DE -.LP -The head of the linked list can be thought of as the data object; -that is, the head is not merely a convenient shorthand for a -structure. Similarly the -.I gn_next -field is used to indicate whether or not the object has terminated. -Unfortunately, if the object continues, the -.I gn_next -field is also the address of where it continues. The link addresses -carry no useful information when the object is serialized. -.LP -The XDR data description of this linked list is described by the -recursive declaration of -.I gnumbers_list : -.ie t .DS -.el .DS L -.ft CW -struct gnumbers { - int g_assets; - int g_liabilities; -}; -.sp .5 -struct gnumbers_node { - gnumbers gn_numbers; - gnumbers_node *gn_next; -}; -.DE -.LP -In this description, the boolean indicates whether there is more data -following it. If the boolean is -.I FALSE , -then it is the last data field of the structure. If it is -.I TRUE , -then it is followed by a gnumbers structure and (recursively) by a -.I gnumbers_list . -Note that the C declaration has no boolean explicitly declared in it -(though the -.I gn_next -field implicitly carries the information), while the XDR data -description has no pointer explicitly declared in it. -.LP -Hints for writing the XDR routines for a -.I gnumbers_list -follow easily from the XDR description above. Note how the primitive -.I xdr_pointer() -is used to implement the XDR union above. -.ie t .DS -.el .DS L -.ft CW -bool_t -xdr_gnumbers_node(xdrs, gn) - XDR *xdrs; - gnumbers_node *gn; -{ - return(xdr_gnumbers(xdrs, &gn->gn_numbers) && - xdr_gnumbers_list(xdrs, &gp->gn_next)); -} -.sp .5 -bool_t -xdr_gnumbers_list(xdrs, gnp) - XDR *xdrs; - gnumbers_list *gnp; -{ - return(xdr_pointer(xdrs, gnp, - sizeof(struct gnumbers_node), - xdr_gnumbers_node)); -} -.DE -.LP -The unfortunate side effect of XDR'ing a list with these routines -is that the C stack grows linearly with respect to the number of -node in the list. This is due to the recursion. The following -routine collapses the above two mutually recursive into a single, -non-recursive one. -.ie t .DS -.el .DS L -.ft CW -bool_t -xdr_gnumbers_list(xdrs, gnp) - XDR *xdrs; - gnumbers_list *gnp; -{ - bool_t more_data; - gnumbers_list *nextp; -.sp .5 - for (;;) { - more_data = (*gnp != NULL); - if (!xdr_bool(xdrs, &more_data)) { - return(FALSE); - } - if (! more_data) { - break; - } - if (xdrs->x_op == XDR_FREE) { - nextp = &(*gnp)->gn_next; - } - if (!xdr_reference(xdrs, gnp, - sizeof(struct gnumbers_node), xdr_gnumbers)) { - - return(FALSE); - } - gnp = (xdrs->x_op == XDR_FREE) ? - nextp : &(*gnp)->gn_next; - } - *gnp = NULL; - return(TRUE); -} -.DE -.LP -The first task is to find out whether there is more data or not, -so that this boolean information can be serialized. Notice that -this statement is unnecessary in the -.I XDR_DECODE -case, since the value of more_data is not known until we -deserialize it in the next statement. -.LP -The next statement XDR's the more_data field of the XDR union. -Then if there is truly no more data, we set this last pointer to -.I NULL -to indicate the end of the list, and return -.I TRUE -because we are done. Note that setting the pointer to -.I NULL -is only important in the -.I XDR_DECODE -case, since it is already -.I NULL -in the -.I XDR_ENCODE -and -XDR_FREE -cases. -.LP -Next, if the direction is -.I XDR_FREE , -the value of -.I nextp -is set to indicate the location of the next pointer in the list. -We do this now because we need to dereference gnp to find the -location of the next item in the list, and after the next -statement the storage pointed to by -.I gnp -will be freed up and no be longer valid. We can't do this for all -directions though, because in the -.I XDR_DECODE -direction the value of -.I gnp -won't be set until the next statement. -.LP -Next, we XDR the data in the node using the primitive -.I xdr_reference (). -.I xdr_reference() -is like -.I xdr_pointer() -which we used before, but it does not -send over the boolean indicating whether there is more data. -We use it instead of -.I xdr_pointer() -because we have already XDR'd this information ourselves. Notice -that the xdr routine passed is not the same type as an element -in the list. The routine passed is -.I xdr_gnumbers (), -for XDR'ing gnumbers, but each element in the list is actually of -type -.I gnumbers_node . -We don't pass -.I xdr_gnumbers_node() -because it is recursive, and instead use -.I xdr_gnumbers() -which XDR's all of the non-recursive part. Note that this trick -will work only if the -.I gn_numbers -field is the first item in each element, so that their addresses -are identical when passed to -.I xdr_reference (). -.LP -Finally, we update -.I gnp -to point to the next item in the list. If the direction is -.I XDR_FREE , -we set it to the previously saved value, otherwise we can -dereference -.I gnp -to get the proper value. Though harder to understand than the -recursive version, this non-recursive routine is far less likely -to blow the C stack. It will also run more efficiently since -a lot of procedure call overhead has been removed. Most lists -are small though (in the hundreds of items or less) and the -recursive version should be sufficient for them. -.EQ -delim off -.EN diff --git a/lib/libc/rpc/PSD.doc/xdr.rfc.ms b/lib/libc/rpc/PSD.doc/xdr.rfc.ms deleted file mode 100644 index 480a339..0000000 --- a/lib/libc/rpc/PSD.doc/xdr.rfc.ms +++ /dev/null @@ -1,1060 +0,0 @@ -.\" -.\" Must use -- tbl -- with this one -.\" -.\" @(#)xdr.rfc.ms 2.2 88/08/05 4.0 RPCSRC -.\" $FreeBSD$ -.\" -.de BT -.if \\n%=1 .tl ''- % -'' -.. -.ND -.\" prevent excess underlining in nroff -.if n .fp 2 R -.OH 'External Data Representation Standard''Page %' -.EH 'Page %''External Data Representation Standard' -.if \n%=1 .bp -.SH -\&External Data Representation Standard: Protocol Specification -.IX "External Data Representation" -.IX XDR RFC -.IX XDR "protocol specification" -.LP -.NH 0 -\&Status of this Standard -.nr OF 1 -.IX XDR "RFC status" -.LP -Note: This chapter specifies a protocol that Sun Microsystems, Inc., and -others are using. It has been designated RFC1014 by the ARPA Network -Information Center. -.NH 1 -Introduction -\& -.LP -XDR is a standard for the description and encoding of data. It is -useful for transferring data between different computer -architectures, and has been used to communicate data between such -diverse machines as the Sun Workstation, VAX, IBM-PC, and Cray. -XDR fits into the ISO presentation layer, and is roughly analogous in -purpose to X.409, ISO Abstract Syntax Notation. The major difference -between these two is that XDR uses implicit typing, while X.409 uses -explicit typing. -.LP -XDR uses a language to describe data formats. The language can only -be used only to describe data; it is not a programming language. -This language allows one to describe intricate data formats in a -concise manner. The alternative of using graphical representations -(itself an informal language) quickly becomes incomprehensible when -faced with complexity. The XDR language itself is similar to the C -language [1], just as Courier [4] is similar to Mesa. Protocols such -as Sun RPC (Remote Procedure Call) and the NFS (Network File System) -use XDR to describe the format of their data. -.LP -The XDR standard makes the following assumption: that bytes (or -octets) are portable, where a byte is defined to be 8 bits of data. -A given hardware device should encode the bytes onto the various -media in such a way that other hardware devices may decode the bytes -without loss of meaning. For example, the Ethernet standard -suggests that bytes be encoded in "little-endian" style [2], or least -significant bit first. -.NH 2 -\&Basic Block Size -.IX XDR "basic block size" -.IX XDR "block size" -.LP -The representation of all items requires a multiple of four bytes (or -32 bits) of data. The bytes are numbered 0 through n-1. The bytes -are read or written to some byte stream such that byte m always -precedes byte m+1. If the n bytes needed to contain the data are not -a multiple of four, then the n bytes are followed by enough (0 to 3) -residual zero bytes, r, to make the total byte count a multiple of 4. -.LP -We include the familiar graphic box notation for illustration and -comparison. In most illustrations, each box (delimited by a plus -sign at the 4 corners and vertical bars and dashes) depicts a byte. -Ellipses (...) between boxes show zero or more additional bytes where -required. -.ie t .DS -.el .DS L -\fIA Block\fP - -\f(CW+--------+--------+...+--------+--------+...+--------+ -| byte 0 | byte 1 |...|byte n-1| 0 |...| 0 | -+--------+--------+...+--------+--------+...+--------+ -|<-----------n bytes---------->|<------r bytes------>| -|<-----------n+r (where (n+r) mod 4 = 0)>----------->|\fP - -.DE -.NH 1 -\&XDR Data Types -.IX XDR "data types" -.IX "XDR data types" -.LP -Each of the sections that follow describes a data type defined in the -XDR standard, shows how it is declared in the language, and includes -a graphic illustration of its encoding. -.LP -For each data type in the language we show a general paradigm -declaration. Note that angle brackets (< and >) denote -variable length sequences of data and square brackets ([ and ]) denote -fixed-length sequences of data. "n", "m" and "r" denote integers. -For the full language specification and more formal definitions of -terms such as "identifier" and "declaration", refer to -.I "The XDR Language Specification" , -below. -.LP -For some data types, more specific examples are included. -A more extensive example of a data description is in -.I "An Example of an XDR Data Description" -below. -.NH 2 -\&Integer -.IX XDR integer -.LP -An XDR signed integer is a 32-bit datum that encodes an integer in -the range [-2147483648,2147483647]. The integer is represented in -two's complement notation. The most and least significant bytes are -0 and 3, respectively. Integers are declared as follows: -.ie t .DS -.el .DS L -\fIInteger\fP - -\f(CW(MSB) (LSB) -+-------+-------+-------+-------+ -|byte 0 |byte 1 |byte 2 |byte 3 | -+-------+-------+-------+-------+ -<------------32 bits------------>\fP -.DE -.NH 2 -\&Unsigned Integer -.IX XDR "unsigned integer" -.IX XDR "integer, unsigned" -.LP -An XDR unsigned integer is a 32-bit datum that encodes a nonnegative -integer in the range [0,4294967295]. It is represented by an -unsigned binary number whose most and least significant bytes are 0 -and 3, respectively. An unsigned integer is declared as follows: -.ie t .DS -.el .DS L -\fIUnsigned Integer\fP - -\f(CW(MSB) (LSB) -+-------+-------+-------+-------+ -|byte 0 |byte 1 |byte 2 |byte 3 | -+-------+-------+-------+-------+ -<------------32 bits------------>\fP -.DE -.NH 2 -\&Enumeration -.IX XDR enumeration -.LP -Enumerations have the same representation as signed integers. -Enumerations are handy for describing subsets of the integers. -Enumerated data is declared as follows: -.ft CW -.DS -enum { name-identifier = constant, ... } identifier; -.DE -For example, the three colors red, yellow, and blue could be -described by an enumerated type: -.DS -.ft CW -enum { RED = 2, YELLOW = 3, BLUE = 5 } colors; -.DE -It is an error to encode as an enum any other integer than those that -have been given assignments in the enum declaration. -.NH 2 -\&Boolean -.IX XDR boolean -.LP -Booleans are important enough and occur frequently enough to warrant -their own explicit type in the standard. Booleans are declared as -follows: -.DS -.ft CW -bool identifier; -.DE -This is equivalent to: -.DS -.ft CW -enum { FALSE = 0, TRUE = 1 } identifier; -.DE -.NH 2 -\&Hyper Integer and Unsigned Hyper Integer -.IX XDR "hyper integer" -.IX XDR "integer, hyper" -.LP -The standard also defines 64-bit (8-byte) numbers called hyper -integer and unsigned hyper integer. Their representations are the -obvious extensions of integer and unsigned integer defined above. -They are represented in two's complement notation. The most and -least significant bytes are 0 and 7, respectively. Their -declarations: -.ie t .DS -.el .DS L -\fIHyper Integer\fP -\fIUnsigned Hyper Integer\fP - -\f(CW(MSB) (LSB) -+-------+-------+-------+-------+-------+-------+-------+-------+ -|byte 0 |byte 1 |byte 2 |byte 3 |byte 4 |byte 5 |byte 6 |byte 7 | -+-------+-------+-------+-------+-------+-------+-------+-------+ -<----------------------------64 bits---------------------------->\fP -.DE -.NH 2 -\&Floating-point -.IX XDR "integer, floating point" -.IX XDR "floating-point integer" -.LP -The standard defines the floating-point data type "float" (32 bits or -4 bytes). The encoding used is the IEEE standard for normalized -single-precision floating-point numbers [3]. The following three -fields describe the single-precision floating-point number: -.RS -.IP \fBS\fP: -The sign of the number. Values 0 and 1 represent positive and -negative, respectively. One bit. -.IP \fBE\fP: -The exponent of the number, base 2. 8 bits are devoted to this -field. The exponent is biased by 127. -.IP \fBF\fP: -The fractional part of the number's mantissa, base 2. 23 bits -are devoted to this field. -.RE -.LP -Therefore, the floating-point number is described by: -.DS -(-1)**S * 2**(E-Bias) * 1.F -.DE -It is declared as follows: -.ie t .DS -.el .DS L -\fISingle-Precision Floating-Point\fP - -\f(CW+-------+-------+-------+-------+ -|byte 0 |byte 1 |byte 2 |byte 3 | -S| E | F | -+-------+-------+-------+-------+ -1|<- 8 ->|<-------23 bits------>| -<------------32 bits------------>\fP -.DE -Just as the most and least significant bytes of a number are 0 and 3, -the most and least significant bits of a single-precision floating- -point number are 0 and 31. The beginning bit (and most significant -bit) offsets of S, E, and F are 0, 1, and 9, respectively. Note that -these numbers refer to the mathematical positions of the bits, and -NOT to their actual physical locations (which vary from medium to -medium). -.LP -The IEEE specifications should be consulted concerning the encoding -for signed zero, signed infinity (overflow), and denormalized numbers -(underflow) [3]. According to IEEE specifications, the "NaN" (not a -number) is system dependent and should not be used externally. -.NH 2 -\&Double-precision Floating-point -.IX XDR "integer, double-precision floating point" -.IX XDR "double-precision floating-point integer" -.LP -The standard defines the encoding for the double-precision floating- -point data type "double" (64 bits or 8 bytes). The encoding used is -the IEEE standard for normalized double-precision floating-point -numbers [3]. The standard encodes the following three fields, which -describe the double-precision floating-point number: -.RS -.IP \fBS\fP: -The sign of the number. Values 0 and 1 represent positive and -negative, respectively. One bit. -.IP \fBE\fP: -The exponent of the number, base 2. 11 bits are devoted to this -field. The exponent is biased by 1023. -.IP \fBF\fP: -The fractional part of the number's mantissa, base 2. 52 bits -are devoted to this field. -.RE -.LP -Therefore, the floating-point number is described by: -.DS -(-1)**S * 2**(E-Bias) * 1.F -.DE -It is declared as follows: -.ie t .DS -.el .DS L -\fIDouble-Precision Floating-Point\fP - -\f(CW+------+------+------+------+------+------+------+------+ -|byte 0|byte 1|byte 2|byte 3|byte 4|byte 5|byte 6|byte 7| -S| E | F | -+------+------+------+------+------+------+------+------+ -1|<--11-->|<-----------------52 bits------------------->| -<-----------------------64 bits------------------------->\fP -.DE -Just as the most and least significant bytes of a number are 0 and 3, -the most and least significant bits of a double-precision floating- -point number are 0 and 63. The beginning bit (and most significant -bit) offsets of S, E , and F are 0, 1, and 12, respectively. Note -that these numbers refer to the mathematical positions of the bits, -and NOT to their actual physical locations (which vary from medium to -medium). -.LP -The IEEE specifications should be consulted concerning the encoding -for signed zero, signed infinity (overflow), and denormalized numbers -(underflow) [3]. According to IEEE specifications, the "NaN" (not a -number) is system dependent and should not be used externally. -.NH 2 -\&Fixed-length Opaque Data -.IX XDR "fixed-length opaque data" -.IX XDR "opaque data, fixed length" -.LP -At times, fixed-length uninterpreted data needs to be passed among -machines. This data is called "opaque" and is declared as follows: -.DS -.ft CW -opaque identifier[n]; -.DE -where the constant n is the (static) number of bytes necessary to -contain the opaque data. If n is not a multiple of four, then the n -bytes are followed by enough (0 to 3) residual zero bytes, r, to make -the total byte count of the opaque object a multiple of four. -.ie t .DS -.el .DS L -\fIFixed-Length Opaque\fP - -\f(CW0 1 ... -+--------+--------+...+--------+--------+...+--------+ -| byte 0 | byte 1 |...|byte n-1| 0 |...| 0 | -+--------+--------+...+--------+--------+...+--------+ -|<-----------n bytes---------->|<------r bytes------>| -|<-----------n+r (where (n+r) mod 4 = 0)------------>|\fP -.DE -.NH 2 -\&Variable-length Opaque Data -.IX XDR "variable-length opaque data" -.IX XDR "opaque data, variable length" -.LP -The standard also provides for variable-length (counted) opaque data, -defined as a sequence of n (numbered 0 through n-1) arbitrary bytes -to be the number n encoded as an unsigned integer (as described -below), and followed by the n bytes of the sequence. -.LP -Byte m of the sequence always precedes byte m+1 of the sequence, and -byte 0 of the sequence always follows the sequence's length (count). -enough (0 to 3) residual zero bytes, r, to make the total byte count -a multiple of four. Variable-length opaque data is declared in the -following way: -.DS -.ft CW -opaque identifier<m>; -.DE -or -.DS -.ft CW -opaque identifier<>; -.DE -The constant m denotes an upper bound of the number of bytes that the -sequence may contain. If m is not specified, as in the second -declaration, it is assumed to be (2**32) - 1, the maximum length. -The constant m would normally be found in a protocol specification. -For example, a filing protocol may state that the maximum data -transfer size is 8192 bytes, as follows: -.DS -.ft CW -opaque filedata<8192>; -.DE -This can be illustrated as follows: -.ie t .DS -.el .DS L -\fIVariable-Length Opaque\fP - -\f(CW0 1 2 3 4 5 ... -+-----+-----+-----+-----+-----+-----+...+-----+-----+...+-----+ -| length n |byte0|byte1|...| n-1 | 0 |...| 0 | -+-----+-----+-----+-----+-----+-----+...+-----+-----+...+-----+ -|<-------4 bytes------->|<------n bytes------>|<---r bytes--->| -|<----n+r (where (n+r) mod 4 = 0)---->|\fP -.DE -.LP -It is an error to encode a length greater than the maximum -described in the specification. -.NH 2 -\&String -.IX XDR string -.LP -The standard defines a string of n (numbered 0 through n-1) ASCII -bytes to be the number n encoded as an unsigned integer (as described -above), and followed by the n bytes of the string. Byte m of the -string always precedes byte m+1 of the string, and byte 0 of the -string always follows the string's length. If n is not a multiple of -four, then the n bytes are followed by enough (0 to 3) residual zero -bytes, r, to make the total byte count a multiple of four. Counted -byte strings are declared as follows: -.DS -.ft CW -string object<m>; -.DE -or -.DS -.ft CW -string object<>; -.DE -The constant m denotes an upper bound of the number of bytes that a -string may contain. If m is not specified, as in the second -declaration, it is assumed to be (2**32) - 1, the maximum length. -The constant m would normally be found in a protocol specification. -For example, a filing protocol may state that a file name can be no -longer than 255 bytes, as follows: -.DS -.ft CW -string filename<255>; -.DE -Which can be illustrated as: -.ie t .DS -.el .DS L -\fIA String\fP - -\f(CW0 1 2 3 4 5 ... -+-----+-----+-----+-----+-----+-----+...+-----+-----+...+-----+ -| length n |byte0|byte1|...| n-1 | 0 |...| 0 | -+-----+-----+-----+-----+-----+-----+...+-----+-----+...+-----+ -|<-------4 bytes------->|<------n bytes------>|<---r bytes--->| -|<----n+r (where (n+r) mod 4 = 0)---->|\fP -.DE -.LP -It is an error to encode a length greater than the maximum -described in the specification. -.NH 2 -\&Fixed-length Array -.IX XDR "fixed-length array" -.IX XDR "array, fixed length" -.LP -Declarations for fixed-length arrays of homogeneous elements are in -the following form: -.DS -.ft CW -type-name identifier[n]; -.DE -Fixed-length arrays of elements numbered 0 through n-1 are encoded by -individually encoding the elements of the array in their natural -order, 0 through n-1. Each element's size is a multiple of four -bytes. Though all elements are of the same type, the elements may -have different sizes. For example, in a fixed-length array of -strings, all elements are of type "string", yet each element will -vary in its length. -.ie t .DS -.el .DS L -\fIFixed-Length Array\fP - -\f(CW+---+---+---+---+---+---+---+---+...+---+---+---+---+ -| element 0 | element 1 |...| element n-1 | -+---+---+---+---+---+---+---+---+...+---+---+---+---+ -|<--------------------n elements------------------->|\fP -.DE -.NH 2 -\&Variable-length Array -.IX XDR "variable-length array" -.IX XDR "array, variable length" -.LP -Counted arrays provide the ability to encode variable-length arrays -of homogeneous elements. The array is encoded as the element count n -(an unsigned integer) followed by the encoding of each of the array's -elements, starting with element 0 and progressing through element n- -1. The declaration for variable-length arrays follows this form: -.DS -.ft CW -type-name identifier<m>; -.DE -or -.DS -.ft CW -type-name identifier<>; -.DE -The constant m specifies the maximum acceptable element count of an -array; if m is not specified, as in the second declaration, it is -assumed to be (2**32) - 1. -.ie t .DS -.el .DS L -\fICounted Array\fP - -\f(CW0 1 2 3 -+--+--+--+--+--+--+--+--+--+--+--+--+...+--+--+--+--+ -| n | element 0 | element 1 |...|element n-1| -+--+--+--+--+--+--+--+--+--+--+--+--+...+--+--+--+--+ -|<-4 bytes->|<--------------n elements------------->|\fP -.DE -It is an error to encode a value of n that is greater than the -maximum described in the specification. -.NH 2 -\&Structure -.IX XDR structure -.LP -Structures are declared as follows: -.DS -.ft CW -struct { - component-declaration-A; - component-declaration-B; - \&... -} identifier; -.DE -The components of the structure are encoded in the order of their -declaration in the structure. Each component's size is a multiple of -four bytes, though the components may be different sizes. -.ie t .DS -.el .DS L -\fIStructure\fP - -\f(CW+-------------+-------------+... -| component A | component B |... -+-------------+-------------+...\fP -.DE -.NH 2 -\&Discriminated Union -.IX XDR "discriminated union" -.IX XDR union discriminated -.LP -A discriminated union is a type composed of a discriminant followed -by a type selected from a set of prearranged types according to the -value of the discriminant. The type of discriminant is either "int", -"unsigned int", or an enumerated type, such as "bool". The component -types are called "arms" of the union, and are preceded by the value -of the discriminant which implies their encoding. Discriminated -unions are declared as follows: -.DS -.ft CW -union switch (discriminant-declaration) { - case discriminant-value-A: - arm-declaration-A; - case discriminant-value-B: - arm-declaration-B; - \&... - default: default-declaration; -} identifier; -.DE -Each "case" keyword is followed by a legal value of the discriminant. -The default arm is optional. If it is not specified, then a valid -encoding of the union cannot take on unspecified discriminant values. -The size of the implied arm is always a multiple of four bytes. -.LP -The discriminated union is encoded as its discriminant followed by -the encoding of the implied arm. -.ie t .DS -.el .DS L -\fIDiscriminated Union\fP - -\f(CW0 1 2 3 -+---+---+---+---+---+---+---+---+ -| discriminant | implied arm | -+---+---+---+---+---+---+---+---+ -|<---4 bytes--->|\fP -.DE -.NH 2 -\&Void -.IX XDR void -.LP -An XDR void is a 0-byte quantity. Voids are useful for describing -operations that take no data as input or no data as output. They are -also useful in unions, where some arms may contain data and others do -not. The declaration is simply as follows: -.DS -.ft CW -void; -.DE -Voids are illustrated as follows: -.ie t .DS -.el .DS L -\fIVoid\fP - -\f(CW ++ - || - ++ ---><-- 0 bytes\fP -.DE -.NH 2 -\&Constant -.IX XDR constant -.LP -The data declaration for a constant follows this form: -.DS -.ft CW -const name-identifier = n; -.DE -"const" is used to define a symbolic name for a constant; it does not -declare any data. The symbolic constant may be used anywhere a -regular constant may be used. For example, the following defines a -symbolic constant DOZEN, equal to 12. -.DS -.ft CW -const DOZEN = 12; -.DE -.NH 2 -\&Typedef -.IX XDR typedef -.LP -"typedef" does not declare any data either, but serves to define new -identifiers for declaring data. The syntax is: -.DS -.ft CW -typedef declaration; -.DE -The new type name is actually the variable name in the declaration -part of the typedef. For example, the following defines a new type -called "eggbox" using an existing type called "egg": -.DS -.ft CW -typedef egg eggbox[DOZEN]; -.DE -Variables declared using the new type name have the same type as the -new type name would have in the typedef, if it was considered a -variable. For example, the following two declarations are equivalent -in declaring the variable "fresheggs": -.DS -.ft CW -eggbox fresheggs; -egg fresheggs[DOZEN]; -.DE -When a typedef involves a struct, enum, or union definition, there is -another (preferred) syntax that may be used to define the same type. -In general, a typedef of the following form: -.DS -.ft CW -typedef <<struct, union, or enum definition>> identifier; -.DE -may be converted to the alternative form by removing the "typedef" -part and placing the identifier after the "struct", "union", or -"enum" keyword, instead of at the end. For example, here are the two -ways to define the type "bool": -.DS -.ft CW -typedef enum { /* \fIusing typedef\fP */ - FALSE = 0, - TRUE = 1 - } bool; - -enum bool { /* \fIpreferred alternative\fP */ - FALSE = 0, - TRUE = 1 - }; -.DE -The reason this syntax is preferred is one does not have to wait -until the end of a declaration to figure out the name of the new -type. -.NH 2 -\&Optional-data -.IX XDR "optional data" -.IX XDR "data, optional" -.LP -Optional-data is one kind of union that occurs so frequently that we -give it a special syntax of its own for declaring it. It is declared -as follows: -.DS -.ft CW -type-name *identifier; -.DE -This is equivalent to the following union: -.DS -.ft CW -union switch (bool opted) { - case TRUE: - type-name element; - case FALSE: - void; -} identifier; -.DE -It is also equivalent to the following variable-length array -declaration, since the boolean "opted" can be interpreted as the -length of the array: -.DS -.ft CW -type-name identifier<1>; -.DE -Optional-data is not so interesting in itself, but it is very useful -for describing recursive data-structures such as linked-lists and -trees. For example, the following defines a type "stringlist" that -encodes lists of arbitrary length strings: -.DS -.ft CW -struct *stringlist { - string item<>; - stringlist next; -}; -.DE -It could have been equivalently declared as the following union: -.DS -.ft CW -union stringlist switch (bool opted) { - case TRUE: - struct { - string item<>; - stringlist next; - } element; - case FALSE: - void; -}; -.DE -or as a variable-length array: -.DS -.ft CW -struct stringlist<1> { - string item<>; - stringlist next; -}; -.DE -Both of these declarations obscure the intention of the stringlist -type, so the optional-data declaration is preferred over both of -them. The optional-data type also has a close correlation to how -recursive data structures are represented in high-level languages -such as Pascal or C by use of pointers. In fact, the syntax is the -same as that of the C language for pointers. -.NH 2 -\&Areas for Future Enhancement -.IX XDR futures -.LP -The XDR standard lacks representations for bit fields and bitmaps, -since the standard is based on bytes. Also missing are packed (or -binary-coded) decimals. -.LP -The intent of the XDR standard was not to describe every kind of data -that people have ever sent or will ever want to send from machine to -machine. Rather, it only describes the most commonly used data-types -of high-level languages such as Pascal or C so that applications -written in these languages will be able to communicate easily over -some medium. -.LP -One could imagine extensions to XDR that would let it describe almost -any existing protocol, such as TCP. The minimum necessary for this -are support for different block sizes and byte-orders. The XDR -discussed here could then be considered the 4-byte big-endian member -of a larger XDR family. -.NH 1 -\&Discussion -.sp 2 -.NH 2 -\&Why a Language for Describing Data? -.IX XDR language -.LP -There are many advantages in using a data-description language such -as XDR versus using diagrams. Languages are more formal than -diagrams and lead to less ambiguous descriptions of data. -Languages are also easier to understand and allow one to think of -other issues instead of the low-level details of bit-encoding. -Also, there is a close analogy between the types of XDR and a -high-level language such as C or Pascal. This makes the -implementation of XDR encoding and decoding modules an easier task. -Finally, the language specification itself is an ASCII string that -can be passed from machine to machine to perform on-the-fly data -interpretation. -.NH 2 -\&Why Only one Byte-Order for an XDR Unit? -.IX XDR "byte order" -.LP -Supporting two byte-orderings requires a higher level protocol for -determining in which byte-order the data is encoded. Since XDR is -not a protocol, this can't be done. The advantage of this, though, -is that data in XDR format can be written to a magnetic tape, for -example, and any machine will be able to interpret it, since no -higher level protocol is necessary for determining the byte-order. -.NH 2 -\&Why does XDR use Big-Endian Byte-Order? -.LP -Yes, it is unfair, but having only one byte-order means you have to -be unfair to somebody. Many architectures, such as the Motorola -68000 and IBM 370, support the big-endian byte-order. -.NH 2 -\&Why is the XDR Unit Four Bytes Wide? -.LP -There is a tradeoff in choosing the XDR unit size. Choosing a small -size such as two makes the encoded data small, but causes alignment -problems for machines that aren't aligned on these boundaries. A -large size such as eight means the data will be aligned on virtually -every machine, but causes the encoded data to grow too big. We chose -four as a compromise. Four is big enough to support most -architectures efficiently, except for rare machines such as the -eight-byte aligned Cray. Four is also small enough to keep the -encoded data restricted to a reasonable size. -.NH 2 -\&Why must Variable-Length Data be Padded with Zeros? -.IX XDR "variable-length data" -.LP -It is desirable that the same data encode into the same thing on all -machines, so that encoded data can be meaningfully compared or -checksummed. Forcing the padded bytes to be zero ensures this. -.NH 2 -\&Why is there No Explicit Data-Typing? -.LP -Data-typing has a relatively high cost for what small advantages it -may have. One cost is the expansion of data due to the inserted type -fields. Another is the added cost of interpreting these type fields -and acting accordingly. And most protocols already know what type -they expect, so data-typing supplies only redundant information. -However, one can still get the benefits of data-typing using XDR. One -way is to encode two things: first a string which is the XDR data -description of the encoded data, and then the encoded data itself. -Another way is to assign a value to all the types in XDR, and then -define a universal type which takes this value as its discriminant -and for each value, describes the corresponding data type. -.NH 1 -\&The XDR Language Specification -.IX XDR language -.sp 1 -.NH 2 -\&Notational Conventions -.IX "XDR language" notation -.LP -This specification uses an extended Backus-Naur Form notation for -describing the XDR language. Here is a brief description of the -notation: -.IP 1. -The characters -.I | , -.I ( , -.I ) , -.I [ , -.I ] , -.I " , -and -.I * -are special. -.IP 2. -Terminal symbols are strings of any characters surrounded by -double quotes. -.IP 3. -Non-terminal symbols are strings of non-special characters. -.IP 4. -Alternative items are separated by a vertical bar ("\fI|\fP"). -.IP 5. -Optional items are enclosed in brackets. -.IP 6. -Items are grouped together by enclosing them in parentheses. -.IP 7. -A -.I * -following an item means 0 or more occurrences of that item. -.LP -For example, consider the following pattern: -.DS L -"a " "very" (", " " very")* [" cold " "and"] " rainy " ("day" | "night") -.DE -.LP -An infinite number of strings match this pattern. A few of them -are: -.DS -"a very rainy day" -"a very, very rainy day" -"a very cold and rainy day" -"a very, very, very cold and rainy night" -.DE -.NH 2 -\&Lexical Notes -.IP 1. -Comments begin with '/*' and terminate with '*/'. -.IP 2. -White space serves to separate items and is otherwise ignored. -.IP 3. -An identifier is a letter followed by an optional sequence of -letters, digits or underbar ('_'). The case of identifiers is -not ignored. -.IP 4. -A constant is a sequence of one or more decimal digits, -optionally preceded by a minus-sign ('-'). -.NH 2 -\&Syntax Information -.IX "XDR language" syntax -.DS -.ft CW -declaration: - type-specifier identifier - | type-specifier identifier "[" value "]" - | type-specifier identifier "<" [ value ] ">" - | "opaque" identifier "[" value "]" - | "opaque" identifier "<" [ value ] ">" - | "string" identifier "<" [ value ] ">" - | type-specifier "*" identifier - | "void" -.DE -.DS -.ft CW -value: - constant - | identifier - -type-specifier: - [ "unsigned" ] "int" - | [ "unsigned" ] "hyper" - | "float" - | "double" - | "bool" - | enum-type-spec - | struct-type-spec - | union-type-spec - | identifier -.DE -.DS -.ft CW -enum-type-spec: - "enum" enum-body - -enum-body: - "{" - ( identifier "=" value ) - ( "," identifier "=" value )* - "}" -.DE -.DS -.ft CW -struct-type-spec: - "struct" struct-body - -struct-body: - "{" - ( declaration ";" ) - ( declaration ";" )* - "}" -.DE -.DS -.ft CW -union-type-spec: - "union" union-body - -union-body: - "switch" "(" declaration ")" "{" - ( "case" value ":" declaration ";" ) - ( "case" value ":" declaration ";" )* - [ "default" ":" declaration ";" ] - "}" - -constant-def: - "const" identifier "=" constant ";" -.DE -.DS -.ft CW -type-def: - "typedef" declaration ";" - | "enum" identifier enum-body ";" - | "struct" identifier struct-body ";" - | "union" identifier union-body ";" - -definition: - type-def - | constant-def - -specification: - definition * -.DE -.NH 3 -\&Syntax Notes -.IX "XDR language" syntax -.LP -.IP 1. -The following are keywords and cannot be used as identifiers: -"bool", "case", "const", "default", "double", "enum", "float", -"hyper", "opaque", "string", "struct", "switch", "typedef", "union", -"unsigned" and "void". -.IP 2. -Only unsigned constants may be used as size specifications for -arrays. If an identifier is used, it must have been declared -previously as an unsigned constant in a "const" definition. -.IP 3. -Constant and type identifiers within the scope of a specification -are in the same name space and must be declared uniquely within this -scope. -.IP 4. -Similarly, variable names must be unique within the scope of -struct and union declarations. Nested struct and union declarations -create new scopes. -.IP 5. -The discriminant of a union must be of a type that evaluates to -an integer. That is, "int", "unsigned int", "bool", an enumerated -type or any typedefed type that evaluates to one of these is legal. -Also, the case values must be one of the legal values of the -discriminant. Finally, a case value may not be specified more than -once within the scope of a union declaration. -.NH 1 -\&An Example of an XDR Data Description -.LP -Here is a short XDR data description of a thing called a "file", -which might be used to transfer files from one machine to another. -.ie t .DS -.el .DS L -.ft CW - -const MAXUSERNAME = 32; /*\fI max length of a user name \fP*/ -const MAXFILELEN = 65535; /*\fI max length of a file \fP*/ -const MAXNAMELEN = 255; /*\fI max length of a file name \fP*/ - -.ft I -/* - * Types of files: - */ -.ft CW - -enum filekind { - TEXT = 0, /*\fI ascii data \fP*/ - DATA = 1, /*\fI raw data \fP*/ - EXEC = 2 /*\fI executable \fP*/ -}; - -.ft I -/* - * File information, per kind of file: - */ -.ft CW - -union filetype switch (filekind kind) { - case TEXT: - void; /*\fI no extra information \fP*/ - case DATA: - string creator<MAXNAMELEN>; /*\fI data creator \fP*/ - case EXEC: - string interpretor<MAXNAMELEN>; /*\fI program interpretor \fP*/ -}; - -.ft I -/* - * A complete file: - */ -.ft CW - -struct file { - string filename<MAXNAMELEN>; /*\fI name of file \fP*/ - filetype type; /*\fI info about file \fP*/ - string owner<MAXUSERNAME>; /*\fI owner of file \fP*/ - opaque data<MAXFILELEN>; /*\fI file data \fP*/ -}; -.DE -.LP -Suppose now that there is a user named "john" who wants to store -his lisp program "sillyprog" that contains just the data "(quit)". -His file would be encoded as follows: -.TS -box tab (&) ; -lfI lfI lfI lfI -rfL rfL rfL l . -Offset&Hex Bytes&ASCII&Description -_ -0&00 00 00 09&....&Length of filename = 9 -4&73 69 6c 6c&sill&Filename characters -8&79 70 72 6f&ypro& ... and more characters ... -12&67 00 00 00&g...& ... and 3 zero-bytes of fill -16&00 00 00 02&....&Filekind is EXEC = 2 -20&00 00 00 04&....&Length of interpretor = 4 -24&6c 69 73 70&lisp&Interpretor characters -28&00 00 00 04&....&Length of owner = 4 -32&6a 6f 68 6e&john&Owner characters -36&00 00 00 06&....&Length of file data = 6 -40&28 71 75 69&(qui&File data bytes ... -44&74 29 00 00&t)..& ... and 2 zero-bytes of fill -.TE -.NH 1 -\&References -.LP -[1] Brian W. Kernighan & Dennis M. Ritchie, "The C Programming -Language", Bell Laboratories, Murray Hill, New Jersey, 1978. -.LP -[2] Danny Cohen, "On Holy Wars and a Plea for Peace", IEEE Computer, -October 1981. -.LP -[3] "IEEE Standard for Binary Floating-Point Arithmetic", ANSI/IEEE -Standard 754-1985, Institute of Electrical and Electronics -Engineers, August 1985. -.LP -[4] "Courier: The Remote Procedure Call Protocol", XEROX -Corporation, XSIS 038112, December 1981. diff --git a/lib/libc/rpc/Symbol.map b/lib/libc/rpc/Symbol.map index ccf0bfa..4f356de 100644 --- a/lib/libc/rpc/Symbol.map +++ b/lib/libc/rpc/Symbol.map @@ -239,10 +239,6 @@ FBSDprivate_1.0 { __key_encryptsession_pk_LOCAL; __key_decryptsession_pk_LOCAL; __key_gendes_LOCAL; - __tsd_lock; /* - * Why does usr.bin/rpcinfo/Makefile need rpc_generic.c? - * Remove this hack if rpcinfo stops building with it. - */ __svc_clean_idle; __rpc_gss_unwrap; __rpc_gss_unwrap_stub; diff --git a/lib/libc/rpc/clnt_simple.c b/lib/libc/rpc/clnt_simple.c index 12b6679..ba21d2d 100644 --- a/lib/libc/rpc/clnt_simple.c +++ b/lib/libc/rpc/clnt_simple.c @@ -76,7 +76,11 @@ struct rpc_call_private { char nettype[NETIDLEN]; /* Network type */ }; static struct rpc_call_private *rpc_call_private_main; +static thread_key_t rpc_call_key; +static once_t rpc_call_once = ONCE_INITIALIZER; +static int rpc_call_key_error; +static void rpc_call_key_init(void); static void rpc_call_destroy(void *); static void @@ -91,6 +95,13 @@ rpc_call_destroy(void *vp) } } +static void +rpc_call_key_init(void) +{ + + rpc_call_key_error = thr_keycreate(&rpc_call_key, rpc_call_destroy); +} + /* * This is the simplified interface to the client rpc layer. * The client handle is not destroyed here and is reused for @@ -112,17 +123,16 @@ rpc_call(host, prognum, versnum, procnum, inproc, in, outproc, out, nettype) struct rpc_call_private *rcp = (struct rpc_call_private *) 0; enum clnt_stat clnt_stat; struct timeval timeout, tottimeout; - static thread_key_t rpc_call_key; int main_thread = 1; if ((main_thread = thr_main())) { rcp = rpc_call_private_main; } else { - if (rpc_call_key == 0) { - mutex_lock(&tsd_lock); - if (rpc_call_key == 0) - thr_keycreate(&rpc_call_key, rpc_call_destroy); - mutex_unlock(&tsd_lock); + if (thr_once(&rpc_call_once, rpc_call_key_init) != 0 || + rpc_call_key_error != 0) { + rpc_createerr.cf_stat = RPC_SYSTEMERROR; + rpc_createerr.cf_error.re_errno = rpc_call_key_error; + return (rpc_createerr.cf_stat); } rcp = (struct rpc_call_private *)thr_getspecific(rpc_call_key); } diff --git a/lib/libc/rpc/getnetconfig.c b/lib/libc/rpc/getnetconfig.c index e5db51a..1310e36 100644 --- a/lib/libc/rpc/getnetconfig.c +++ b/lib/libc/rpc/getnetconfig.c @@ -130,21 +130,29 @@ static struct netconfig *dup_ncp(struct netconfig *); static FILE *nc_file; /* for netconfig db */ -static pthread_mutex_t nc_file_lock = PTHREAD_MUTEX_INITIALIZER; +static mutex_t nc_file_lock = MUTEX_INITIALIZER; static struct netconfig_info ni = { 0, 0, NULL, NULL}; -static pthread_mutex_t ni_lock = PTHREAD_MUTEX_INITIALIZER; +static mutex_t ni_lock = MUTEX_INITIALIZER; +static thread_key_t nc_key; +static once_t nc_once = ONCE_INITIALIZER; +static int nc_key_error; + +static void +nc_key_init(void) +{ + + nc_key_error = thr_keycreate(&nc_key, free); +} #define MAXNETCONFIGLINE 1000 static int * __nc_error() { - static pthread_mutex_t nc_lock = PTHREAD_MUTEX_INITIALIZER; - static thread_key_t nc_key = 0; static int nc_error = 0; - int error, *nc_addr; + int *nc_addr; /* * Use the static `nc_error' if we are the main thread @@ -153,15 +161,8 @@ __nc_error() */ if (thr_main()) return (&nc_error); - if (nc_key == 0) { - error = 0; - mutex_lock(&nc_lock); - if (nc_key == 0) - error = thr_keycreate(&nc_key, free); - mutex_unlock(&nc_lock); - if (error) - return (&nc_error); - } + if (thr_once(&nc_once, nc_key_init) != 0 || nc_key_error != 0) + return (&nc_error); if ((nc_addr = (int *)thr_getspecific(nc_key)) == NULL) { nc_addr = (int *)malloc(sizeof (int)); if (thr_setspecific(nc_key, (void *) nc_addr) != 0) { diff --git a/lib/libc/rpc/key_call.c b/lib/libc/rpc/key_call.c index 6cc1139..afb11c8 100644 --- a/lib/libc/rpc/key_call.c +++ b/lib/libc/rpc/key_call.c @@ -279,6 +279,9 @@ struct key_call_private { uid_t uid; /* user-id at last authorization */ }; static struct key_call_private *key_call_private_main = NULL; +static thread_key_t key_call_key; +static once_t key_call_once = ONCE_INITIALIZER; +static int key_call_key_error; static void key_call_destroy(void *vp) @@ -292,6 +295,13 @@ key_call_destroy(void *vp) } } +static void +key_call_init(void) +{ + + key_call_key_error = thr_keycreate(&key_call_key, key_call_destroy); +} + /* * Keep the handle cached. This call may be made quite often. */ @@ -307,7 +317,6 @@ int vers; struct utsname u; int main_thread; int fd; - static thread_key_t key_call_key; #define TOTAL_TIMEOUT 30 /* total timeout talking to keyserver */ #define TOTAL_TRIES 5 /* Number of tries */ @@ -315,12 +324,9 @@ int vers; if ((main_thread = thr_main())) { kcp = key_call_private_main; } else { - if (key_call_key == 0) { - mutex_lock(&tsd_lock); - if (key_call_key == 0) - thr_keycreate(&key_call_key, key_call_destroy); - mutex_unlock(&tsd_lock); - } + if (thr_once(&key_call_once, key_call_init) != 0 || + key_call_key_error != 0) + return ((CLIENT *) NULL); kcp = (struct key_call_private *)thr_getspecific(key_call_key); } if (kcp == (struct key_call_private *)NULL) { diff --git a/lib/libc/rpc/mt_misc.c b/lib/libc/rpc/mt_misc.c index 6241611..7abcaed 100644 --- a/lib/libc/rpc/mt_misc.c +++ b/lib/libc/rpc/mt_misc.c @@ -28,7 +28,6 @@ __FBSDID("$FreeBSD$"); #define proglst_lock __proglst_lock #define rpcsoc_lock __rpcsoc_lock #define svcraw_lock __svcraw_lock -#define tsd_lock __tsd_lock #define xprtlist_lock __xprtlist_lock /* protects the services list (svc.c) */ @@ -76,33 +75,33 @@ pthread_mutex_t rpcsoc_lock = PTHREAD_MUTEX_INITIALIZER; /* svc_raw.c serialization */ pthread_mutex_t svcraw_lock = PTHREAD_MUTEX_INITIALIZER; -/* protects TSD key creation */ -pthread_mutex_t tsd_lock = PTHREAD_MUTEX_INITIALIZER; - /* xprtlist (svc_generic.c) */ pthread_mutex_t xprtlist_lock = PTHREAD_MUTEX_INITIALIZER; #undef rpc_createerr struct rpc_createerr rpc_createerr; +static thread_key_t rce_key; +static once_t rce_once = ONCE_INITIALIZER; +static int rce_key_error; + +static void +rce_key_init(void) +{ + + rce_key_error = thr_keycreate(&rce_key, free); +} struct rpc_createerr * __rpc_createerr() { - static thread_key_t rce_key = 0; struct rpc_createerr *rce_addr = 0; if (thr_main()) return (&rpc_createerr); - if ((rce_addr = - (struct rpc_createerr *)thr_getspecific(rce_key)) != 0) { - mutex_lock(&tsd_lock); - if (thr_keycreate(&rce_key, free) != 0) { - mutex_unlock(&tsd_lock); - return (&rpc_createerr); - } - mutex_unlock(&tsd_lock); - } + if (thr_once(&rce_once, rce_key_init) != 0 || rce_key_error != 0) + return (&rpc_createerr); + rce_addr = (struct rpc_createerr *)thr_getspecific(rce_key); if (!rce_addr) { rce_addr = (struct rpc_createerr *) malloc(sizeof (struct rpc_createerr)); diff --git a/lib/libc/rpc/mt_misc.h b/lib/libc/rpc/mt_misc.h index e785c30..9cc2349 100644 --- a/lib/libc/rpc/mt_misc.h +++ b/lib/libc/rpc/mt_misc.h @@ -42,7 +42,6 @@ #define proglst_lock __proglst_lock #define rpcsoc_lock __rpcsoc_lock #define svcraw_lock __svcraw_lock -#define tsd_lock __tsd_lock #define xprtlist_lock __xprtlist_lock extern pthread_rwlock_t svc_lock; diff --git a/lib/libc/rpc/rpc_generic.c b/lib/libc/rpc/rpc_generic.c index 81bd92b..ab259d5 100644 --- a/lib/libc/rpc/rpc_generic.c +++ b/lib/libc/rpc/rpc_generic.c @@ -221,6 +221,18 @@ getnettype(nettype) return (_rpctypelist[i].type); } +static thread_key_t tcp_key, udp_key; +static once_t keys_once = ONCE_INITIALIZER; +static int tcp_key_error, udp_key_error; + +static void +keys_init(void) +{ + + tcp_key_error = thr_keycreate(&tcp_key, free); + udp_key_error = thr_keycreate(&udp_key, free); +} + /* * For the given nettype (tcp or udp only), return the first structure found. * This should be freed by calling freenetconfigent() @@ -236,25 +248,15 @@ __rpc_getconfip(nettype) static char *netid_udp_main; struct netconfig *dummy; int main_thread; - static thread_key_t tcp_key, udp_key; if ((main_thread = thr_main())) { netid_udp = netid_udp_main; netid_tcp = netid_tcp_main; } else { - if (tcp_key == 0) { - mutex_lock(&tsd_lock); - if (tcp_key == 0) - thr_keycreate(&tcp_key, free); - mutex_unlock(&tsd_lock); - } + if (thr_once(&keys_once, keys_init) != 0 || + tcp_key_error != 0 || udp_key_error != 0) + return (NULL); netid_tcp = (char *)thr_getspecific(tcp_key); - if (udp_key == 0) { - mutex_lock(&tsd_lock); - if (udp_key == 0) - thr_keycreate(&udp_key, free); - mutex_unlock(&tsd_lock); - } netid_udp = (char *)thr_getspecific(udp_key); } if (!netid_udp && !netid_tcp) { diff --git a/lib/libc/rpc/rpc_soc.c b/lib/libc/rpc/rpc_soc.c index 5922063..2568d43 100644 --- a/lib/libc/rpc/rpc_soc.c +++ b/lib/libc/rpc/rpc_soc.c @@ -360,6 +360,14 @@ registerrpc(prognum, versnum, procnum, progname, inproc, outproc) */ static thread_key_t clnt_broadcast_key; static resultproc_t clnt_broadcast_result_main; +static once_t clnt_broadcast_once = ONCE_INITIALIZER; + +static void +clnt_broadcast_key_init(void) +{ + + thr_keycreate(&clnt_broadcast_key, free); +} /* * Need to translate the netbuf address into sockaddr_in address. @@ -402,12 +410,7 @@ clnt_broadcast(prog, vers, proc, xargs, argsp, xresults, resultsp, eachresult) if (thr_main()) clnt_broadcast_result_main = eachresult; else { - if (clnt_broadcast_key == 0) { - mutex_lock(&tsd_lock); - if (clnt_broadcast_key == 0) - thr_keycreate(&clnt_broadcast_key, free); - mutex_unlock(&tsd_lock); - } + thr_once(&clnt_broadcast_once, clnt_broadcast_key_init); thr_setspecific(clnt_broadcast_key, (void *) eachresult); } return rpc_broadcast((rpcprog_t)prog, (rpcvers_t)vers, diff --git a/lib/libc/rpc/svc_vc.c b/lib/libc/rpc/svc_vc.c index 3fd8b7e..aded6b1 100644 --- a/lib/libc/rpc/svc_vc.c +++ b/lib/libc/rpc/svc_vc.c @@ -546,7 +546,7 @@ write_vc(xprtp, buf, len) cd->strm_stat = XPRT_DIED; return (-1); } - if (cd->nonblock && i != cnt) { + if (cd->nonblock) { /* * For non-blocking connections, do not * take more than 2 seconds writing the @@ -560,6 +560,7 @@ write_vc(xprtp, buf, len) return (-1); } } + i = 0; } } diff --git a/lib/libc/softfloat/Makefile.inc b/lib/libc/softfloat/Makefile.inc index c786761..ac7fbf7 100644 --- a/lib/libc/softfloat/Makefile.inc +++ b/lib/libc/softfloat/Makefile.inc @@ -2,10 +2,10 @@ # $FreeBSD$ SOFTFLOAT_BITS?=64 -.PATH: ${MACHINE_ARCH}/softfloat \ +.PATH: ${LIBC_ARCH}/softfloat \ ${.CURDIR}/softfloat/bits${SOFTFLOAT_BITS} ${.CURDIR}/softfloat -CFLAGS+= -I${.CURDIR}/${MACHINE_ARCH}/softfloat -I${.CURDIR}/softfloat +CFLAGS+= -I${.CURDIR}/${LIBC_ARCH}/softfloat -I${.CURDIR}/softfloat CFLAGS+= -DSOFTFLOAT_FOR_GCC SRCS+= softfloat.c diff --git a/lib/libc/softfloat/softfloat-specialize b/lib/libc/softfloat/softfloat-specialize index c8c8028..e8585ce 100644 --- a/lib/libc/softfloat/softfloat-specialize +++ b/lib/libc/softfloat/softfloat-specialize @@ -44,7 +44,11 @@ Underflow tininess-detection mode, statically initialized to default value. #ifdef SOFTFLOAT_FOR_GCC static #endif +#ifdef __sparc64__ +int8 float_detect_tininess = float_tininess_before_rounding; +#else int8 float_detect_tininess = float_tininess_after_rounding; +#endif /* ------------------------------------------------------------------------------- diff --git a/lib/libc/sparc64/fpu/fpu.c b/lib/libc/sparc64/fpu/fpu.c index 74f07ec..4e92788 100644 --- a/lib/libc/sparc64/fpu/fpu.c +++ b/lib/libc/sparc64/fpu/fpu.c @@ -69,9 +69,12 @@ __FBSDID("$FreeBSD$"); #include "namespace.h" #include <errno.h> -#include <unistd.h> #include <signal.h> +#ifdef FPU_DEBUG +#include <stdio.h> +#endif #include <stdlib.h> +#include <unistd.h> #include "un-namespace.h" #include "libc_private.h" @@ -97,7 +100,7 @@ __FBSDID("$FreeBSD$"); #define X8(x) X4(x),X4(x) #define X16(x) X8(x),X8(x) -static char cx_to_trapx[] = { +static const char cx_to_trapx[] = { X1(FSR_NX), X2(FSR_DZ), X4(FSR_UF), @@ -113,7 +116,8 @@ int __fpe_debug = 0; #endif #endif /* FPU_DEBUG */ -static int __fpu_execute(struct utrapframe *, struct fpemu *, u_int32_t, u_long); +static int __fpu_execute(struct utrapframe *, struct fpemu *, u_int32_t, + u_long); /* * Need to use an fpstate on the stack; we could switch, so we cannot safely @@ -169,7 +173,7 @@ __fpu_exception(struct utrapframe *uf) void __fpu_dumpfpn(struct fpn *fp) { - static char *class[] = { + static const char *const class[] = { "SNAN", "QNAN", "ZERO", "NUM", "INF" }; @@ -181,15 +185,11 @@ __fpu_dumpfpn(struct fpn *fp) } #endif -static int opmask[] = {0, 0, 1, 3}; +static const int opmask[] = {0, 0, 1, 3, 1}; /* Decode 5 bit register field depending on the type. */ #define RN_DECODE(tp, rn) \ - ((tp == FTYPE_DBL || tp == FTYPE_EXT ? INSFPdq_RN((rn)) : (rn)) & \ - ~opmask[tp]) - -/* Operand size in 32-bit registers. */ -#define OPSZ(tp) ((tp) == FTYPE_LNG ? 2 : (1 << (tp))) + ((tp) >= FTYPE_DBL ? INSFPdq_RN(rn) & ~opmask[tp] : (rn)) /* * Helper for forming the below case statements. Build only the op3 and opf @@ -209,8 +209,6 @@ static void __fpu_mov(struct fpemu *fe, int type, int rd, int rs2, u_int32_t nand, u_int32_t xor) { - u_int64_t tmp64; - int i; if (type == FTYPE_INT || type == FTYPE_SNG) __fpu_setreg(rd, (__fpu_getreg(rs2) & ~nand) ^ xor); @@ -219,13 +217,10 @@ __fpu_mov(struct fpemu *fe, int type, int rd, int rs2, u_int32_t nand, * Need to use the double versions to be able to access * the upper 32 fp registers. */ - for (i = 0; i < OPSZ(type); i += 2, rd += 2, rs2 += 2) { - tmp64 = __fpu_getreg64(rs2); - if (i == 0) - tmp64 = (tmp64 & ~((u_int64_t)nand << 32)) ^ - ((u_int64_t)xor << 32); - __fpu_setreg64(rd, tmp64); - } + __fpu_setreg64(rd, (__fpu_getreg64(rs2) & + ~((u_int64_t)nand << 32)) ^ ((u_int64_t)xor << 32)); + if (type == FTYPE_EXT) + __fpu_setreg64(rd + 2, __fpu_getreg64(rs2 + 2)); } } @@ -271,17 +266,17 @@ __fpu_cmpck(struct fpemu *fe) * multiply two integers this way. */ static int -__fpu_execute(struct utrapframe *uf, struct fpemu *fe, u_int32_t insn, u_long tstate) +__fpu_execute(struct utrapframe *uf, struct fpemu *fe, u_int32_t insn, + u_long tstate) { struct fpn *fp; int opf, rs1, rs2, rd, type, mask, cx, cond; u_long reg, fsr; u_int space[4]; - int i; /* * `Decode' and execute instruction. Start with no exceptions. - * The type of any opf opcode is in the bottom two bits, so we + * The type of almost any OPF opcode is in the bottom two bits, so we * squish them out here. */ opf = insn & (IF_MASK(IF_F3_OP3_SHIFT, IF_F3_OP3_BITS) | @@ -359,7 +354,7 @@ __fpu_execute(struct utrapframe *uf, struct fpemu *fe, u_int32_t insn, u_long ts __fpu_explode(fe, &fe->fe_f2, type, rs2); __fpu_compare(fe, 1, IF_F3_CC(insn)); return (__fpu_cmpck(fe)); - case FOP(INS2_FPop1, INSFP1_FMOV): /* these should all be pretty obvious */ + case FOP(INS2_FPop1, INSFP1_FMOV): __fpu_mov(fe, type, rd, rs2, 0, 0); return (0); case FOP(INS2_FPop1, INSFP1_FNEG): @@ -410,6 +405,7 @@ __fpu_execute(struct utrapframe *uf, struct fpemu *fe, u_int32_t insn, u_long ts case FOP(INS2_FPop1, INSFP1_FxTOd): case FOP(INS2_FPop1, INSFP1_FxTOq): type = FTYPE_LNG; + rs2 = RN_DECODE(type, IF_F3_RS2(insn)); __fpu_explode(fe, fp = &fe->fe_f1, type, rs2); /* sneaky; depends on instruction encoding */ type = (IF_F3_OPF(insn) >> 2) & 3; @@ -418,8 +414,7 @@ __fpu_execute(struct utrapframe *uf, struct fpemu *fe, u_int32_t insn, u_long ts case FOP(INS2_FPop1, INSFP1_FTOx): __fpu_explode(fe, fp = &fe->fe_f1, type, rs2); type = FTYPE_LNG; - mask = 1; /* needs 2 registers */ - rd = IF_F3_RD(insn) & ~mask; + rd = RN_DECODE(type, IF_F3_RD(insn)); break; case FOP(INS2_FPop1, INSFP1_FTOs): case FOP(INS2_FPop1, INSFP1_FTOd): @@ -457,10 +452,10 @@ __fpu_execute(struct utrapframe *uf, struct fpemu *fe, u_int32_t insn, u_long ts if (type == FTYPE_INT || type == FTYPE_SNG) __fpu_setreg(rd, space[0]); else { - for (i = 0; i < OPSZ(type); i += 2) { - __fpu_setreg64(rd + i, ((u_int64_t)space[i] << 32) | - space[i + 1]); - } + __fpu_setreg64(rd, ((u_int64_t)space[0] << 32) | space[1]); + if (type == FTYPE_EXT) + __fpu_setreg64(rd + 2, + ((u_int64_t)space[2] << 32) | space[3]); } return (0); /* success */ } diff --git a/lib/libc/sparc64/fpu/fpu_div.c b/lib/libc/sparc64/fpu/fpu_div.c index c4b8ef6..4748daf 100644 --- a/lib/libc/sparc64/fpu/fpu_div.c +++ b/lib/libc/sparc64/fpu/fpu_div.c @@ -167,14 +167,16 @@ __fpu_div(fe) * return it. Otherwise we have the following cases: * * Inf / Inf = NaN, plus NV exception - * Inf / num = Inf [i.e., return x] - * Inf / 0 = Inf [i.e., return x] - * 0 / Inf = 0 [i.e., return x] - * 0 / num = 0 [i.e., return x] + * Inf / num = Inf [i.e., return x #] + * Inf / 0 = Inf [i.e., return x #] + * 0 / Inf = 0 [i.e., return x #] + * 0 / num = 0 [i.e., return x #] * 0 / 0 = NaN, plus NV exception - * num / Inf = 0 + * num / Inf = 0 # * num / num = num (do the divide) - * num / 0 = Inf, plus DZ exception + * num / 0 = Inf #, plus DZ exception + * + * # Sign of result is XOR of operand signs. */ if (ISNAN(x) || ISNAN(y)) { ORDER(x, y); @@ -183,10 +185,10 @@ __fpu_div(fe) if (ISINF(x) || ISZERO(x)) { if (x->fp_class == y->fp_class) return (__fpu_newnan(fe)); + x->fp_sign ^= y->fp_sign; return (x); } - /* all results at this point use XOR of operand signs */ x->fp_sign ^= y->fp_sign; if (ISINF(y)) { x->fp_class = FPC_ZERO; diff --git a/lib/libc/sparc64/fpu/fpu_emu.h b/lib/libc/sparc64/fpu/fpu_emu.h index de156e2..0d1d16d 100644 --- a/lib/libc/sparc64/fpu/fpu_emu.h +++ b/lib/libc/sparc64/fpu/fpu_emu.h @@ -140,7 +140,7 @@ struct fpn { #define FTYPE_SNG INSFP_s #define FTYPE_DBL INSFP_d #define FTYPE_EXT INSFP_q -#define FTYPE_LNG -1 +#define FTYPE_LNG 4 /* * Emulator state. diff --git a/lib/libc/sparc64/fpu/fpu_explode.c b/lib/libc/sparc64/fpu/fpu_explode.c index 09cfd5a..474e0df 100644 --- a/lib/libc/sparc64/fpu/fpu_explode.c +++ b/lib/libc/sparc64/fpu/fpu_explode.c @@ -49,6 +49,10 @@ __FBSDID("$FreeBSD$"); #include <sys/param.h> +#ifdef FPU_DEBUG +#include <stdio.h> +#endif + #include <machine/frame.h> #include <machine/fp.h> #include <machine/fsr.h> @@ -135,9 +139,9 @@ __fpu_xtof(fp, i) * a signed or unsigned entity. */ if (fp->fp_sign && (int64_t)i < 0) - *((int64_t*)fp->fp_mant) = -i; + *((int64_t *)fp->fp_mant) = -i; else - *((int64_t*)fp->fp_mant) = i; + *((int64_t *)fp->fp_mant) = i; fp->fp_mant[2] = 0; fp->fp_mant[3] = 0; __fpu_norm(fp); @@ -258,14 +262,12 @@ __fpu_explode(fe, fp, type, reg) struct fpn *fp; int type, reg; { - u_int32_t s, *sp; - u_int64_t l[2]; - void *vl = l; + u_int64_t l0, l1; + u_int32_t s; if (type == FTYPE_LNG || type == FTYPE_DBL || type == FTYPE_EXT) { - l[0] = __fpu_getreg64(reg & ~1); - sp = vl; - fp->fp_sign = sp[0] >> 31; + l0 = __fpu_getreg64(reg & ~1); + fp->fp_sign = l0 >> 63; } else { s = __fpu_getreg(reg); fp->fp_sign = s >> 31; @@ -273,7 +275,7 @@ __fpu_explode(fe, fp, type, reg) fp->fp_sticky = 0; switch (type) { case FTYPE_LNG: - s = __fpu_xtof(fp, l[0]); + s = __fpu_xtof(fp, l0); break; case FTYPE_INT: @@ -285,12 +287,13 @@ __fpu_explode(fe, fp, type, reg) break; case FTYPE_DBL: - s = __fpu_dtof(fp, sp[0], sp[1]); + s = __fpu_dtof(fp, l0 >> 32, l0 & 0xffffffff); break; case FTYPE_EXT: - l[1] = __fpu_getreg64((reg & ~1) + 2); - s = __fpu_qtof(fp, sp[0], sp[1], sp[2], sp[3]); + l1 = __fpu_getreg64((reg & ~1) + 2); + s = __fpu_qtof(fp, l0 >> 32, l0 & 0xffffffff, l1 >> 32, + l1 & 0xffffffff); break; default: diff --git a/lib/libc/sparc64/fpu/fpu_extern.h b/lib/libc/sparc64/fpu/fpu_extern.h index 3567edf..a5fb942 100644 --- a/lib/libc/sparc64/fpu/fpu_extern.h +++ b/lib/libc/sparc64/fpu/fpu_extern.h @@ -34,7 +34,6 @@ #define _SPARC64_FPU_FPU_EXTERN_H_ struct utrapframe; -union instr; struct fpemu; struct fpn; @@ -54,9 +53,9 @@ struct fpn *__fpu_div(struct fpemu *); int __fpu_itof(struct fpn *, u_int); int __fpu_xtof(struct fpn *, u_int64_t); int __fpu_stof(struct fpn *, u_int); -int __fpu_dtof(struct fpn *, u_int, u_int ); -int __fpu_qtof(struct fpn *, u_int, u_int , u_int , u_int ); -void __fpu_explode(struct fpemu *, struct fpn *, int, int ); +int __fpu_dtof(struct fpn *, u_int, u_int); +int __fpu_qtof(struct fpn *, u_int, u_int, u_int, u_int); +void __fpu_explode(struct fpemu *, struct fpn *, int, int); /* fpu_implode.c */ u_int __fpu_ftoi(struct fpemu *, struct fpn *); diff --git a/lib/libc/sparc64/fpu/fpu_implode.c b/lib/libc/sparc64/fpu/fpu_implode.c index 5287d2b..2a2a9d0 100644 --- a/lib/libc/sparc64/fpu/fpu_implode.c +++ b/lib/libc/sparc64/fpu/fpu_implode.c @@ -49,6 +49,10 @@ __FBSDID("$FreeBSD$"); #include <sys/param.h> +#ifdef FPU_DEBUG +#include <stdio.h> +#endif + #include <machine/frame.h> #include <machine/fp.h> #include <machine/fsr.h> @@ -198,7 +202,6 @@ __fpu_ftoi(fe, fp) sign = fp->fp_sign; switch (fp->fp_class) { - case FPC_ZERO: return (0); @@ -248,10 +251,9 @@ __fpu_ftox(fe, fp, res) sign = fp->fp_sign; switch (fp->fp_class) { - case FPC_ZERO: - res[1] = 0; - return (0); + i = 0; + goto done; case FPC_NUM: /* @@ -275,15 +277,17 @@ __fpu_ftox(fe, fp, res) break; if (sign) i = -i; - res[1] = (int)i; - return (i >> 32); + goto done; default: /* Inf, qNaN, sNaN */ break; } /* overflow: replace any inexact exception with invalid */ fe->fe_cx = (fe->fe_cx & ~FSR_NX) | FSR_NV; - return (0x7fffffffffffffffLL + sign); + i = 0x7fffffffffffffffLL + sign; +done: + res[1] = i & 0xffffffff; + return (i >> 32); } /* @@ -325,8 +329,9 @@ __fpu_ftos(fe, fp) * right to introduce leading zeroes. Rounding then acts * differently for normals and subnormals: the largest subnormal * may round to the smallest normal (1.0 x 2^minexp), or may - * remain subnormal. In the latter case, signal an underflow - * if the result was inexact or if underflow traps are enabled. + * remain subnormal. A number that is subnormal before rounding + * will signal an underflow if the result is inexact or if underflow + * traps are enabled. * * Rounding a normal, on the other hand, always produces another * normal (although either way the result might be too big for @@ -341,8 +346,10 @@ __fpu_ftos(fe, fp) if ((exp = fp->fp_exp + SNG_EXP_BIAS) <= 0) { /* subnormal */ /* -NG for g,r; -SNG_FRACBITS-exp for fraction */ (void) __fpu_shr(fp, FP_NMANT - FP_NG - SNG_FRACBITS - exp); - if (fpround(fe, fp) && fp->fp_mant[3] == SNG_EXP(1)) + if (fpround(fe, fp) && fp->fp_mant[3] == SNG_EXP(1)) { + fe->fe_cx |= FSR_UF; return (sign | SNG_EXP(1) | 0); + } if ((fe->fe_cx & FSR_NX) || (fe->fe_fsr & (FSR_UF << FSR_TEM_SHIFT))) fe->fe_cx |= FSR_UF; @@ -403,6 +410,7 @@ zero: res[1] = 0; if ((exp = fp->fp_exp + DBL_EXP_BIAS) <= 0) { (void) __fpu_shr(fp, FP_NMANT - FP_NG - DBL_FRACBITS - exp); if (fpround(fe, fp) && fp->fp_mant[2] == DBL_EXP(1)) { + fe->fe_cx |= FSR_UF; res[1] = 0; return (sign | DBL_EXP(1) | 0); } @@ -422,7 +430,7 @@ zero: res[1] = 0; return (sign | DBL_EXP(DBL_EXP_INFNAN) | 0); } res[1] = ~0; - return (sign | DBL_EXP(DBL_EXP_INFNAN) | DBL_MASK); + return (sign | DBL_EXP(DBL_EXP_INFNAN - 1) | DBL_MASK); } done: res[1] = fp->fp_mant[3]; @@ -464,6 +472,7 @@ zero: res[1] = res[2] = res[3] = 0; if ((exp = fp->fp_exp + EXT_EXP_BIAS) <= 0) { (void) __fpu_shr(fp, FP_NMANT - FP_NG - EXT_FRACBITS - exp); if (fpround(fe, fp) && fp->fp_mant[0] == EXT_EXP(1)) { + fe->fe_cx |= FSR_UF; res[1] = res[2] = res[3] = 0; return (sign | EXT_EXP(1) | 0); } @@ -483,7 +492,7 @@ zero: res[1] = res[2] = res[3] = 0; return (sign | EXT_EXP(EXT_EXP_INFNAN) | 0); } res[1] = res[2] = res[3] = ~0; - return (sign | EXT_EXP(EXT_EXP_INFNAN) | EXT_MASK); + return (sign | EXT_EXP(EXT_EXP_INFNAN - 1) | EXT_MASK); } done: res[1] = fp->fp_mant[1]; @@ -504,7 +513,6 @@ __fpu_implode(fe, fp, type, space) { switch (type) { - case FTYPE_LNG: space[0] = __fpu_ftox(fe, fp, space); break; diff --git a/lib/libc/sparc64/sys/Makefile.inc b/lib/libc/sparc64/sys/Makefile.inc index 43e4edb..dedf783 100644 --- a/lib/libc/sparc64/sys/Makefile.inc +++ b/lib/libc/sparc64/sys/Makefile.inc @@ -11,9 +11,6 @@ SRCS+= __sparc_sigtramp_setup.c \ sigcode.S CFLAGS+= -I${.CURDIR}/sparc64/fpu -.if ${MACHINE} == "sun4v" -CFLAGS+= -DSUN4V -.endif MDASM+= brk.S cerror.S exect.S pipe.S ptrace.S sbrk.S setlogin.S sigaction.S diff --git a/lib/libc/sparc64/sys/__sparc_utrap_gen.S b/lib/libc/sparc64/sys/__sparc_utrap_gen.S index 4fb128d..6f6f0e3 100644 --- a/lib/libc/sparc64/sys/__sparc_utrap_gen.S +++ b/lib/libc/sparc64/sys/__sparc_utrap_gen.S @@ -38,10 +38,6 @@ __FBSDID("$FreeBSD$"); #include "assym.s" ENTRY(__sparc_utrap_gen) -#ifdef SUN4V - save - ta %xcc, ST_FPEMU_CONTEXT -#endif sub %sp, UF_SIZEOF, %sp stx %o0, [%sp + SPOFF + CCFSZ + UF_TYPE] diff --git a/lib/libc/stdio/fgets.3 b/lib/libc/stdio/fgets.3 index aa8e2ac..fba7353 100644 --- a/lib/libc/stdio/fgets.3 +++ b/lib/libc/stdio/fgets.3 @@ -128,6 +128,19 @@ 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 , +.Xr fgetws 3 , +.Xr getline 3 +.Sh STANDARDS +The functions +.Fn fgets +and +.Fn gets +conform to +.St -isoC-99 . .Sh SECURITY CONSIDERATIONS The .Fn gets @@ -143,16 +156,3 @@ It is strongly suggested that the function be used in all cases. (See the FSA.) -.Sh SEE ALSO -.Xr feof 3 , -.Xr ferror 3 , -.Xr fgetln 3 , -.Xr fgetws 3 , -.Xr getline 3 -.Sh STANDARDS -The functions -.Fn fgets -and -.Fn gets -conform to -.St -isoC-99 . diff --git a/lib/libc/stdio/findfp.c b/lib/libc/stdio/findfp.c index 5bc4af7..89c0536 100644 --- a/lib/libc/stdio/findfp.c +++ b/lib/libc/stdio/findfp.c @@ -61,6 +61,7 @@ int __sdidinit; ._read = __sread, \ ._seek = __sseek, \ ._write = __swrite, \ + ._fl_mutex = PTHREAD_MUTEX_INITIALIZER, \ } /* the usual - (stdin + stdout + stderr) */ static FILE usual[FOPEN_MAX - 3]; @@ -96,7 +97,7 @@ moreglue(n) int n; { struct glue *g; - static FILE empty; + static FILE empty = { ._fl_mutex = PTHREAD_MUTEX_INITIALIZER }; FILE *p; g = (struct glue *)malloc(sizeof(*g) + ALIGNBYTES + n * sizeof(FILE)); @@ -154,7 +155,7 @@ found: fp->_ub._size = 0; fp->_lb._base = NULL; /* no line buffer */ fp->_lb._size = 0; -/* fp->_lock = NULL; */ /* once set always set (reused) */ +/* fp->_fl_mutex = NULL; */ /* once set always set (reused) */ fp->_orientation = 0; memset(&fp->_mbstate, 0, sizeof(mbstate_t)); return (fp); diff --git a/lib/libc/stdio/fopen.3 b/lib/libc/stdio/fopen.3 index 92ec1e2..5c1f2b1 100644 --- a/lib/libc/stdio/fopen.3 +++ b/lib/libc/stdio/fopen.3 @@ -104,7 +104,7 @@ This is strictly for compatibility with and has no effect; the ``b'' is ignored. .Pp Any created files will have mode -.Pf \\*q Dv S_IRUSR +.Do Dv S_IRUSR \&| .Dv S_IWUSR \&| @@ -114,7 +114,7 @@ Any created files will have mode \&| .Dv S_IROTH \&| -.Dv S_IWOTH Ns \\*q +.Dv S_IWOTH Dc .Pq Li 0666 , as modified by the process' umask value (see diff --git a/lib/libc/stdio/freopen.c b/lib/libc/stdio/freopen.c index d718496..be7bc8a 100644 --- a/lib/libc/stdio/freopen.c +++ b/lib/libc/stdio/freopen.c @@ -150,14 +150,6 @@ freopen(file, mode, fp) /* 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: @@ -165,9 +157,11 @@ finish: * 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. + * + * Leave the existing file descriptor open until dup2() is called + * below to avoid races where a concurrent open() in another thread + * could claim the existing descriptor. */ - if (isopen) - (void) (*fp->_close)(fp->_cookie); if (fp->_flags & __SMBF) free((char *)fp->_bf._base); fp->_w = 0; @@ -186,6 +180,8 @@ finish: memset(&fp->_mbstate, 0, sizeof(mbstate_t)); if (f < 0) { /* did not get it after all */ + if (isopen) + (void) (*fp->_close)(fp->_cookie); fp->_flags = 0; /* set it free */ FUNLOCKFILE(fp); errno = sverrno; /* restore in case _close clobbered */ @@ -197,11 +193,12 @@ finish: * 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 (wantfd >= 0) { if (_dup2(f, wantfd) >= 0) { (void)_close(f); f = wantfd; - } + } else + (void)_close(fp->_file); } /* diff --git a/lib/libc/stdio/getline.3 b/lib/libc/stdio/getline.3 index a5b39da..e0dda08 100644 --- a/lib/libc/stdio/getline.3 +++ b/lib/libc/stdio/getline.3 @@ -24,7 +24,7 @@ .\" .\" $FreeBSD$ .\" -.Dd March 29, 2009 +.Dd November 30, 2010 .Dt GETLINE 3 .Os .Sh NAME @@ -54,23 +54,23 @@ function is equivalent to with the newline character as the delimiter. The delimiter character is included as part of the line, unless the end of the file is reached. -The caller may provide a pointer to a malloc buffer for the line in +.Pp +The caller may provide a pointer to a malloced buffer for the line in .Fa *linep , and the capacity of that buffer in -.Fa *linecapp ; -if -.Fa *linecapp -is 0, then -.Fa *linep -is treated as -.Dv NULL . -These functions may expand the buffer as needed, as if via -.Fn realloc , -and update +.Fa *linecapp . +These functions expand the buffer as needed, as if via +.Fn realloc . +If +.Fa linep +points to a +.Dv NULL +pointer, a new buffer will be allocated. +In either case, .Fa *linep and .Fa *linecapp -accordingly. +will be updated accordingly. .Sh RETURN VALUES The .Fn getdelim @@ -140,7 +140,7 @@ No delimiter was found in the first characters. .El .Pp -These functions may also fail for any of the errors specified for +These functions may also fail due to any of the errors specified for .Fn fgets and .Fn malloc . diff --git a/lib/libc/stdio/local.h b/lib/libc/stdio/local.h index 09b3a18..6380b83 100644 --- a/lib/libc/stdio/local.h +++ b/lib/libc/stdio/local.h @@ -110,6 +110,14 @@ extern int __sdidinit; } /* + * Structure initializations for 'fake' FILE objects. + */ +#define FAKE_FILE { \ + ._file = -1, \ + ._fl_mutex = PTHREAD_MUTEX_INITIALIZER, \ +} + +/* * Set the orientation for a stream. If o > 0, the stream has wide- * orientation. If o < 0, the stream has byte-orientation. */ diff --git a/lib/libc/stdio/printf-pos.c b/lib/libc/stdio/printf-pos.c index 1648957..c42bd85 100644 --- a/lib/libc/stdio/printf-pos.c +++ b/lib/libc/stdio/printf-pos.c @@ -248,7 +248,6 @@ __find_arguments (const char *fmt0, va_list ap, union arg **argtable) int n; /* handy integer (short term usage) */ int error; int flags; /* flags as above */ - int width; /* width from format (%8d), or 0 */ struct typetable types; /* table of types */ fmt = (char *)fmt0; @@ -266,7 +265,6 @@ __find_arguments (const char *fmt0, va_list ap, union arg **argtable) fmt++; /* skip over '%' */ flags = 0; - width = 0; rflag: ch = *fmt++; reswitch: switch (ch) { @@ -304,7 +302,6 @@ reswitch: switch (ch) { types.nextarg = n; goto rflag; } - width = n; goto reswitch; #ifndef NO_FLOATING_POINT case 'L': @@ -439,7 +436,6 @@ __find_warguments (const wchar_t *fmt0, va_list ap, union arg **argtable) int n; /* handy integer (short term usage) */ int error; int flags; /* flags as above */ - int width; /* width from format (%8d), or 0 */ struct typetable types; /* table of types */ fmt = (wchar_t *)fmt0; @@ -457,7 +453,6 @@ __find_warguments (const wchar_t *fmt0, va_list ap, union arg **argtable) fmt++; /* skip over '%' */ flags = 0; - width = 0; rflag: ch = *fmt++; reswitch: switch (ch) { @@ -495,7 +490,6 @@ reswitch: switch (ch) { types.nextarg = n; goto rflag; } - width = n; goto reswitch; #ifndef NO_FLOATING_POINT case 'L': diff --git a/lib/libc/stdio/printf.3 b/lib/libc/stdio/printf.3 index 8de2bb8..90a8ed8 100644 --- a/lib/libc/stdio/printf.3 +++ b/lib/libc/stdio/printf.3 @@ -449,7 +449,7 @@ 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 +.Oo \- Oc Ar d Li \&. Ar ddd Li e \(+- Ar dd .Sm on where there is one digit before the decimal-point character @@ -525,7 +525,7 @@ 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 , +.Oo \- Oc Li 0x Ar h Li \&. Ar hhhp Oo \(+- Oc Ar d , .Sm on where the number of digits after the hexadecimal-point character is equal to the precision specification. @@ -709,77 +709,6 @@ char *newfmt(const char *fmt, ...) return (p); } .Ed -.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);" .Sh COMPATIBILITY Many application writers used the name .Va dprintf @@ -891,9 +820,9 @@ in .Fx 2.2 , but were later replaced with a different implementation from -.An Todd C. Miller Aq Todd.Miller@courtesan.com -for -.Ox 2.3 . +.Ox 2.3 +by +.An Todd C. Miller Aq Todd.Miller@courtesan.com . The .Fn dprintf and @@ -906,3 +835,74 @@ The 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/libc/stdio/snprintf.c b/lib/libc/stdio/snprintf.c index 0470a33..e6d7115 100644 --- a/lib/libc/stdio/snprintf.c +++ b/lib/libc/stdio/snprintf.c @@ -48,7 +48,7 @@ snprintf(char * __restrict str, size_t n, char const * __restrict fmt, ...) size_t on; int ret; va_list ap; - FILE f; + FILE f = FAKE_FILE; on = n; if (n != 0) @@ -56,12 +56,9 @@ snprintf(char * __restrict str, size_t n, char const * __restrict fmt, ...) if (n > INT_MAX) n = INT_MAX; va_start(ap, fmt); - f._file = -1; f._flags = __SWR | __SSTR; f._bf._base = f._p = (unsigned char *)str; f._bf._size = f._w = n; - f._orientation = 0; - memset(&f._mbstate, 0, sizeof(mbstate_t)); ret = __vfprintf(&f, fmt, ap); if (on > 0) *f._p = '\0'; diff --git a/lib/libc/stdio/tmpnam.3 b/lib/libc/stdio/tmpnam.3 index 66652b7..937068f 100644 --- a/lib/libc/stdio/tmpnam.3 +++ b/lib/libc/stdio/tmpnam.3 @@ -217,6 +217,17 @@ 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 -isoC . .Sh SECURITY CONSIDERATIONS The .Fn tmpnam @@ -235,14 +246,3 @@ It is strongly suggested that be used in place of these functions. (See the FSA.) -.Sh SEE ALSO -.Xr mkstemp 3 , -.Xr mktemp 3 -.Sh STANDARDS -The -.Fn tmpfile -and -.Fn tmpnam -functions -conform to -.St -isoC . diff --git a/lib/libc/stdio/vasprintf.c b/lib/libc/stdio/vasprintf.c index 0682b5b..a1b600a 100644 --- a/lib/libc/stdio/vasprintf.c +++ b/lib/libc/stdio/vasprintf.c @@ -36,25 +36,19 @@ __FBSDID("$FreeBSD$"); #include "local.h" int -vasprintf(str, fmt, ap) - char **str; - const char *fmt; - __va_list ap; +vasprintf(char **str, const char *fmt, __va_list ap) { + FILE f = FAKE_FILE; int ret; - FILE f; - f._file = -1; f._flags = __SWR | __SSTR | __SALC; - f._bf._base = f._p = (unsigned char *)malloc(128); + f._bf._base = f._p = malloc(128); if (f._bf._base == NULL) { *str = NULL; errno = ENOMEM; return (-1); } f._bf._size = f._w = 127; /* Leave room for the NUL */ - f._orientation = 0; - memset(&f._mbstate, 0, sizeof(mbstate_t)); ret = __vfprintf(&f, fmt, ap); if (ret < 0) { free(f._bf._base); diff --git a/lib/libc/stdio/vdprintf.c b/lib/libc/stdio/vdprintf.c index 2703022..3ad273e 100644 --- a/lib/libc/stdio/vdprintf.c +++ b/lib/libc/stdio/vdprintf.c @@ -39,7 +39,7 @@ __FBSDID("$FreeBSD$"); int vdprintf(int fd, const char * __restrict fmt, va_list ap) { - FILE f; + FILE f = FAKE_FILE; unsigned char buf[BUFSIZ]; int ret; @@ -56,8 +56,6 @@ vdprintf(int fd, const char * __restrict fmt, va_list ap) f._write = __swrite; f._bf._base = buf; f._bf._size = sizeof(buf); - f._orientation = 0; - bzero(&f._mbstate, sizeof(f._mbstate)); if ((ret = __vfprintf(&f, fmt, ap)) < 0) return (ret); diff --git a/lib/libc/stdio/vfprintf.c b/lib/libc/stdio/vfprintf.c index 7e5d7fe..17ad824 100644 --- a/lib/libc/stdio/vfprintf.c +++ b/lib/libc/stdio/vfprintf.c @@ -169,7 +169,7 @@ static int __sbprintf(FILE *fp, const char *fmt, va_list ap) { int ret; - FILE fake; + FILE fake = FAKE_FILE; unsigned char buf[BUFSIZ]; /* XXX This is probably not needed. */ diff --git a/lib/libc/stdio/vsnprintf.c b/lib/libc/stdio/vsnprintf.c index f990664..70e4c53 100644 --- a/lib/libc/stdio/vsnprintf.c +++ b/lib/libc/stdio/vsnprintf.c @@ -47,7 +47,7 @@ vsnprintf(char * __restrict str, size_t n, const char * __restrict fmt, size_t on; int ret; char dummy[2]; - FILE f; + FILE f = FAKE_FILE; on = n; if (n != 0) @@ -61,12 +61,9 @@ vsnprintf(char * __restrict str, size_t n, const char * __restrict fmt, str = dummy; n = 1; } - f._file = -1; f._flags = __SWR | __SSTR; f._bf._base = f._p = (unsigned char *)str; f._bf._size = f._w = n; - f._orientation = 0; - memset(&f._mbstate, 0, sizeof(mbstate_t)); ret = __vfprintf(&f, fmt, ap); if (on > 0) *f._p = '\0'; diff --git a/lib/libc/stdio/vsprintf.c b/lib/libc/stdio/vsprintf.c index 60d830c..3890af7 100644 --- a/lib/libc/stdio/vsprintf.c +++ b/lib/libc/stdio/vsprintf.c @@ -44,14 +44,11 @@ int vsprintf(char * __restrict str, const char * __restrict fmt, __va_list ap) { int ret; - FILE f; + FILE f = FAKE_FILE; - f._file = -1; f._flags = __SWR | __SSTR; f._bf._base = f._p = (unsigned char *)str; f._bf._size = f._w = INT_MAX; - f._orientation = 0; - memset(&f._mbstate, 0, sizeof(mbstate_t)); ret = __vfprintf(&f, fmt, ap); *f._p = 0; return (ret); diff --git a/lib/libc/stdio/vsscanf.c b/lib/libc/stdio/vsscanf.c index 22b5d2b..82429c6 100644 --- a/lib/libc/stdio/vsscanf.c +++ b/lib/libc/stdio/vsscanf.c @@ -55,16 +55,11 @@ int vsscanf(const char * __restrict str, const char * __restrict fmt, __va_list ap) { - FILE f; + FILE f = FAKE_FILE; - f._file = -1; f._flags = __SRD; f._bf._base = f._p = (unsigned char *)str; f._bf._size = f._r = strlen(str); f._read = eofread; - f._ub._base = NULL; - f._lb._base = NULL; - f._orientation = 0; - memset(&f._mbstate, 0, sizeof(mbstate_t)); return (__svfscanf(&f, fmt, ap)); } diff --git a/lib/libc/stdio/vswprintf.c b/lib/libc/stdio/vswprintf.c index 61b8720..2cfe724 100644 --- a/lib/libc/stdio/vswprintf.c +++ b/lib/libc/stdio/vswprintf.c @@ -45,7 +45,7 @@ vswprintf(wchar_t * __restrict s, size_t n, const wchar_t * __restrict fmt, { static const mbstate_t initial; mbstate_t mbs; - FILE f; + FILE f = FAKE_FILE; char *mbp; int ret, sverrno; size_t nwc; @@ -55,7 +55,6 @@ vswprintf(wchar_t * __restrict s, size_t n, const wchar_t * __restrict fmt, return (-1); } - f._file = -1; f._flags = __SWR | __SSTR | __SALC; f._bf._base = f._p = (unsigned char *)malloc(128); if (f._bf._base == NULL) { @@ -63,8 +62,6 @@ vswprintf(wchar_t * __restrict s, size_t n, const wchar_t * __restrict fmt, return (-1); } f._bf._size = f._w = 127; /* Leave room for the NUL */ - f._orientation = 0; - memset(&f._mbstate, 0, sizeof(mbstate_t)); ret = __vfwprintf(&f, fmt, ap); if (ret < 0) { sverrno = errno; diff --git a/lib/libc/stdio/vswscanf.c b/lib/libc/stdio/vswscanf.c index 8a70d44..f06fc02 100644 --- a/lib/libc/stdio/vswscanf.c +++ b/lib/libc/stdio/vswscanf.c @@ -62,7 +62,7 @@ vswscanf(const wchar_t * __restrict str, const wchar_t * __restrict fmt, { static const mbstate_t initial; mbstate_t mbs; - FILE f; + FILE f = FAKE_FILE; char *mbstr; size_t mlen; int r; @@ -80,15 +80,10 @@ vswscanf(const wchar_t * __restrict str, const wchar_t * __restrict fmt, free(mbstr); return (EOF); } - f._file = -1; f._flags = __SRD; f._bf._base = f._p = (unsigned char *)mbstr; f._bf._size = f._r = mlen; f._read = eofread; - f._ub._base = NULL; - f._lb._base = NULL; - f._orientation = 0; - memset(&f._mbstate, 0, sizeof(mbstate_t)); r = __vfwscanf(&f, fmt, ap); free(mbstr); diff --git a/lib/libc/stdio/wprintf.3 b/lib/libc/stdio/wprintf.3 index d9e724f..fecb586 100644 --- a/lib/libc/stdio/wprintf.3 +++ b/lib/libc/stdio/wprintf.3 @@ -376,7 +376,7 @@ 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 +.Oo \- Oc Ar d Li \&. Ar ddd Li e \(+- Ar dd .Sm on where there is one digit before the decimal-point character @@ -452,7 +452,7 @@ 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 , +.Oo \- Oc Li 0x Ar h Li \&. Ar hhhp Oo \(+- Oc Ar d , .Sm on where the number of digits after the hexadecimal-point character is equal to the precision specification. @@ -588,9 +588,6 @@ 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 SECURITY CONSIDERATIONS -Refer to -.Xr printf 3 . .Sh SEE ALSO .Xr btowc 3 , .Xr fputws 3 , @@ -616,3 +613,6 @@ and functions conform to .St -isoC-99 . +.Sh SECURITY CONSIDERATIONS +Refer to +.Xr printf 3 . diff --git a/lib/libc/stdio/xprintf.c b/lib/libc/stdio/xprintf.c index bb41a9c..0cc8571 100644 --- a/lib/libc/stdio/xprintf.c +++ b/lib/libc/stdio/xprintf.c @@ -48,6 +48,7 @@ #include <wchar.h> #include "un-namespace.h" +#include "local.h" #include "printf.h" #include "fvwrite.h" @@ -575,7 +576,7 @@ static int __v3printf(FILE *fp, const char *fmt, int pct, va_list ap) { int ret; - FILE fake; + FILE fake = FAKE_FILE; unsigned char buf[BUFSIZ]; /* copy the important variables */ diff --git a/lib/libc/stdio/xprintf_time.c b/lib/libc/stdio/xprintf_time.c index 9d732fe..debfac5 100644 --- a/lib/libc/stdio/xprintf_time.c +++ b/lib/libc/stdio/xprintf_time.c @@ -62,7 +62,7 @@ __printf_render_time(struct __printf_io *io, const struct printf_info *pi, const struct timespec *ts; time_t *tp; intmax_t t, tx; - int i, prec, nsec; + int i, prec, nsec, ret; if (pi->is_long) { tv = *((struct timeval **)arg[0]); @@ -80,6 +80,12 @@ __printf_render_time(struct __printf_io *io, const struct printf_info *pi, const nsec = 0; prec = 0; } + if (pi->is_long || pi->is_long_double) { + if (pi->prec >= 0) + prec = pi->prec; + if (prec == 0) + nsec = 0; + } p = buf; if (pi->alt) { @@ -88,29 +94,29 @@ __printf_render_time(struct __printf_io *io, const struct printf_info *pi, const p += sprintf(p, "%jdy", t / YEAR); t %= YEAR; } - if (t >= DAY && t != 0) { + if (tx >= DAY && (t != 0 || prec != 0)) { p += sprintf(p, "%jdd", t / DAY); t %= DAY; } - if (t >= HOUR && t != 0) { + if (tx >= HOUR && (t != 0 || prec != 0)) { p += sprintf(p, "%jdh", t / HOUR); t %= HOUR; } - if (t >= MINUTE && t != 0) { + if (tx >= MINUTE && (t != 0 || prec != 0)) { p += sprintf(p, "%jdm", t / MINUTE); t %= MINUTE; } - if (t != 0 || tx == 0) + if (t != 0 || tx == 0 || prec != 0) p += sprintf(p, "%jds", t); } else { p += sprintf(p, "%jd", (intmax_t)t); } - if (pi->is_long || pi->is_long_double) { - if (pi->prec >= 0) - prec = pi->prec; + if (prec != 0) { for (i = prec; i < 9; i++) nsec /= 10; p += sprintf(p, ".%.*d", prec, nsec); } - return(__printf_out(io, pi, buf, p - buf)); + ret = __printf_out(io, pi, buf, p - buf); + __printf_flush(io); + return (ret); } diff --git a/lib/libc/stdlib/Makefile.inc b/lib/libc/stdlib/Makefile.inc index 1d06dd3..d5b151c 100644 --- a/lib/libc/stdlib/Makefile.inc +++ b/lib/libc/stdlib/Makefile.inc @@ -2,7 +2,7 @@ # $FreeBSD$ # machine-independent stdlib sources -.PATH: ${.CURDIR}/${MACHINE_ARCH}/stdlib ${.CURDIR}/stdlib +.PATH: ${.CURDIR}/${LIBC_ARCH}/stdlib ${.CURDIR}/stdlib MISRCS+=_Exit.c a64l.c abort.c abs.c atexit.c atof.c atoi.c atol.c atoll.c \ bsearch.c div.c exit.c getenv.c getopt.c getopt_long.c \ @@ -16,7 +16,7 @@ MISRCS+=_Exit.c a64l.c abort.c abs.c atexit.c atof.c atoi.c atol.c atoll.c \ SYM_MAPS+= ${.CURDIR}/stdlib/Symbol.map # machine-dependent stdlib sources -.sinclude "${.CURDIR}/${MACHINE_ARCH}/stdlib/Makefile.inc" +.sinclude "${.CURDIR}/${LIBC_ARCH}/stdlib/Makefile.inc" MAN+= a64l.3 abort.3 abs.3 alloca.3 atexit.3 atof.3 atoi.3 atol.3 bsearch.3 \ div.3 exit.3 getenv.3 getopt.3 getopt_long.3 getsubopt.3 \ @@ -51,3 +51,7 @@ MLINKS+=tsearch.3 tdelete.3 tsearch.3 tfind.3 tsearch.3 twalk.3 CFLAGS+= -DMALLOC_PRODUCTION .endif +.if ${CC:T:Mclang} == "clang" +# XXX: Temporary workaround for LLVM PR 9352 +CFLAGS+= ${.IMPSRC:T:Mmalloc.c:C/^.+$/-no-integrated-as/} +.endif diff --git a/lib/libc/stdlib/atexit.c b/lib/libc/stdlib/atexit.c index efd1264..511172a 100644 --- a/lib/libc/stdlib/atexit.c +++ b/lib/libc/stdlib/atexit.c @@ -37,6 +37,7 @@ static char sccsid[] = "@(#)atexit.c 8.2 (Berkeley) 7/3/94"; __FBSDID("$FreeBSD$"); #include "namespace.h" +#include <link.h> #include <stddef.h> #include <stdlib.h> #include <unistd.h> @@ -54,6 +55,7 @@ static pthread_mutex_t atexit_mutex = PTHREAD_MUTEX_INITIALIZER; #define _MUTEX_LOCK(x) if (__isthreaded) _pthread_mutex_lock(x) #define _MUTEX_UNLOCK(x) if (__isthreaded) _pthread_mutex_unlock(x) +#define _MUTEX_DESTROY(x) if (__isthreaded) _pthread_mutex_destroy(x) struct atexit { struct atexit *next; /* next in list */ @@ -119,7 +121,7 @@ atexit(void (*func)(void)) int error; fn.fn_type = ATEXIT_FN_STD; - fn.fn_ptr.std_func = func;; + fn.fn_ptr.std_func = func; fn.fn_arg = NULL; fn.fn_dso = NULL; @@ -138,7 +140,7 @@ __cxa_atexit(void (*func)(void *), void *arg, void *dso) int error; fn.fn_type = ATEXIT_FN_CXA; - fn.fn_ptr.cxa_func = func;; + fn.fn_ptr.cxa_func = func; fn.fn_arg = arg; fn.fn_dso = dso; @@ -146,6 +148,9 @@ __cxa_atexit(void (*func)(void *), void *arg, void *dso) return (error); } +#pragma weak __pthread_cxa_finalize +void __pthread_cxa_finalize(const struct dl_phdr_info *); + /* * Call all handlers registered with __cxa_atexit for the shared * object owning 'dso'. Note: if 'dso' is NULL, then all remaining @@ -154,18 +159,28 @@ __cxa_atexit(void (*func)(void *), void *arg, void *dso) void __cxa_finalize(void *dso) { + struct dl_phdr_info phdr_info; struct atexit *p; struct atexit_fn fn; - int n; + int n, has_phdr; + + if (dso != NULL) + has_phdr = _rtld_addr_phdr(dso, &phdr_info); + else + has_phdr = 0; _MUTEX_LOCK(&atexit_mutex); for (p = __atexit; p; p = p->next) { for (n = p->ind; --n >= 0;) { if (p->fns[n].fn_type == ATEXIT_FN_EMPTY) continue; /* already been called */ - if (dso != NULL && dso != p->fns[n].fn_dso) - continue; /* wrong DSO */ fn = p->fns[n]; + if (dso != NULL && dso != fn.fn_dso) { + /* wrong DSO ? */ + if (!has_phdr || !__elf_phdr_match_addr( + &phdr_info, fn.fn_ptr.cxa_func)) + continue; + } /* Mark entry to indicate that this particular handler has already been called. @@ -182,4 +197,9 @@ __cxa_finalize(void *dso) } } _MUTEX_UNLOCK(&atexit_mutex); + if (dso == NULL) + _MUTEX_DESTROY(&atexit_mutex); + + if (has_phdr && &__pthread_cxa_finalize != NULL) + __pthread_cxa_finalize(&phdr_info); } diff --git a/lib/libc/stdlib/getopt.3 b/lib/libc/stdlib/getopt.3 index a966624..3fe4453 100644 --- a/lib/libc/stdlib/getopt.3 +++ b/lib/libc/stdlib/getopt.3 @@ -66,11 +66,11 @@ 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 -.Li "\&""x"" +.Li \&"x" recognizes an option .Dq Fl x , and an option string -.Li "\&""x:"" +.Li \&"x:" recognizes an option and argument .Dq Fl x Ar argument . It does not matter to diff --git a/lib/libc/stdlib/getopt_long.3 b/lib/libc/stdlib/getopt_long.3 index 352af08..72f6534 100644 --- a/lib/libc/stdlib/getopt_long.3 +++ b/lib/libc/stdlib/getopt_long.3 @@ -469,9 +469,9 @@ The .Fn getopt_long and .Fn getopt_long_only -functions first appeared in +functions first appeared in the .Tn GNU -libiberty. +libiberty library. The first .Bx implementation of diff --git a/lib/libc/stdlib/hcreate.3 b/lib/libc/stdlib/hcreate.3 index cd82720..2466c9f 100644 --- a/lib/libc/stdlib/hcreate.3 +++ b/lib/libc/stdlib/hcreate.3 @@ -29,8 +29,8 @@ .\" $FreeBSD$ .\" .Dd July 6, 2008 -.Os .Dt HCREATE 3 +.Os .Sh NAME .Nm hcreate , hdestroy , hsearch .Nd manage hash search table diff --git a/lib/libc/stdlib/malloc.3 b/lib/libc/stdlib/malloc.3 index 9b9fe96..5f09733 100644 --- a/lib/libc/stdlib/malloc.3 +++ b/lib/libc/stdlib/malloc.3 @@ -218,7 +218,7 @@ thread-specific cache garbage collection sweeps. Garbage collection is actually performed incrementally, one size class at a time, in order to avoid large collection pauses. The default sweep interval is 8192; -.Ev JEMALLOC_OPTIONS=14g +.Ev MALLOC_OPTIONS=14g will disable garbage collection. .It H Double/halve the number of thread-specific cache slots per size @@ -232,7 +232,7 @@ See the .Dq G option for related tuning information. The default number of cache slots is 128; -.Ev JEMALLOC_OPTIONS=7h +.Ev MALLOC_OPTIONS=7h will disable thread-specific caching. Note that one cache slot per size class is not a valid configuration due to implementation details. @@ -415,7 +415,7 @@ Allocation requests that are more than half the quantum, but no more than the minimum cacheline-multiple size class (see the .Dq Q option) are rounded up to the nearest multiple of the quantum. -Allocation requests that are more than the minumum cacheline-multiple size +Allocation requests that are more than the minimum cacheline-multiple size class, but no more than the minimum subpage-multiple size class (see the .Dq C option) are rounded up to the nearest multiple of the cacheline size (64). @@ -550,7 +550,6 @@ allocation functions. .El .Sh EXAMPLES To dump core whenever a problem occurs: -.Pp .Bd -literal -offset indent ln -s 'A' /etc/malloc.conf .Ed diff --git a/lib/libc/stdlib/malloc.c b/lib/libc/stdlib/malloc.c index 295a168..48d9c14 100644 --- a/lib/libc/stdlib/malloc.c +++ b/lib/libc/stdlib/malloc.c @@ -180,6 +180,7 @@ __FBSDID("$FreeBSD$"); #include <errno.h> #include <limits.h> +#include <link.h> #include <pthread.h> #include <sched.h> #include <stdarg.h> @@ -194,6 +195,8 @@ __FBSDID("$FreeBSD$"); #include "un-namespace.h" +#include "libc_private.h" + #define RB_COMPACT #include "rb.h" #if (defined(MALLOC_TCACHE) && defined(MALLOC_STATS)) @@ -231,7 +234,7 @@ __FBSDID("$FreeBSD$"); #ifdef __sparc64__ # define LG_QUANTUM 4 # define LG_SIZEOF_PTR 3 -# define NO_TLS +# define TLS_MODEL /* default */ #endif #ifdef __amd64__ # define LG_QUANTUM 4 @@ -249,8 +252,13 @@ __FBSDID("$FreeBSD$"); # define LG_SIZEOF_PTR 2 # define NO_TLS #endif -#ifdef __powerpc__ +#ifdef __powerpc64__ +# define LG_QUANTUM 4 +# define LG_SIZEOF_PTR 3 +# define TLS_MODEL /* default */ +#elif defined(__powerpc__) # define LG_QUANTUM 4 +# define LG_SIZEOF_PTR 2 # define TLS_MODEL /* default */ #endif #ifdef __s390x__ @@ -5348,14 +5356,20 @@ small_size2bin_init_hard(void) static unsigned malloc_ncpus(void) { + int mib[2]; unsigned ret; - size_t retlen = sizeof(ret); - int mib[] = {CTL_HW, HW_NCPU}; - - if (sysctl(mib, sizeof(mib) / sizeof(int), &ret, &retlen, - (void *)0, 0) == -1) { - /* Error. */ - ret = 1; + int error; + size_t len; + + error = _elf_aux_info(AT_NCPUS, &ret, sizeof(ret)); + if (error != 0 || ret == 0) { + mib[0] = CTL_HW; + mib[1] = HW_NCPU; + len = sizeof(ret); + if (sysctl(mib, 2, &ret, &len, (void *)NULL, 0) == -1) { + /* Error. */ + ret = 1; + } } return (ret); diff --git a/lib/libc/stdlib/ptsname.3 b/lib/libc/stdlib/ptsname.3 index f674a54..48da3bd 100644 --- a/lib/libc/stdlib/ptsname.3 +++ b/lib/libc/stdlib/ptsname.3 @@ -32,8 +32,8 @@ .\" $FreeBSD$ .\" .Dd August 20, 2008 -.Os .Dt PTSNAME 3 +.Os .Sh NAME .Nm grantpt , .Nm ptsname , diff --git a/lib/libc/stdlib/rand.3 b/lib/libc/stdlib/rand.3 index 9b24795..3eb1a1d 100644 --- a/lib/libc/stdlib/rand.3 +++ b/lib/libc/stdlib/rand.3 @@ -32,7 +32,7 @@ .\" @(#)rand.3 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd May 25, 1999 +.Dd October 6, 2010 .Dt RAND 3 .Os .Sh NAME @@ -100,7 +100,16 @@ provides the same functionality as A pointer to the context value .Fa ctx must be supplied by the caller. +.Pp +For better generator quality, use +.Xr random 3 +or +.Xr lrand48 3 . +Applications requiring cryptographic quality randomness should use +.Xr arc4random 3 . .Sh SEE ALSO +.Xr arc4random 3 , +.Xr lrand48 3 , .Xr random 3 , .Xr random 4 .Sh STANDARDS diff --git a/lib/libc/stdlib/random.3 b/lib/libc/stdlib/random.3 index aacf6e3..c6502bf 100644 --- a/lib/libc/stdlib/random.3 +++ b/lib/libc/stdlib/random.3 @@ -173,6 +173,7 @@ detects that the state information has been garbled, error messages are printed on the standard error output. .Sh SEE ALSO .Xr arc4random 3 , +.Xr lrand48 3 , .Xr rand 3 , .Xr srand 3 , .Xr random 4 diff --git a/lib/libc/stdlib/realpath.3 b/lib/libc/stdlib/realpath.3 index 4205a3d..fec5258 100644 --- a/lib/libc/stdlib/realpath.3 +++ b/lib/libc/stdlib/realpath.3 @@ -31,7 +31,7 @@ .\" @(#)realpath.3 8.2 (Berkeley) 2/16/94 .\" $FreeBSD$ .\" -.Dd February 16, 1994 +.Dd April 19, 2010 .Dt REALPATH 3 .Os .Sh NAME @@ -43,7 +43,7 @@ .In sys/param.h .In stdlib.h .Ft "char *" -.Fn realpath "const char *pathname" "char resolved_path[PATH_MAX]" +.Fn realpath "const char *pathname" "char *resolved_path" .Sh DESCRIPTION The .Fn realpath @@ -56,15 +56,16 @@ and in .Fa pathname , and copies the resulting absolute pathname into -the memory referenced by +the memory pointed to by .Fa resolved_path . The .Fa resolved_path argument .Em must -refer to a buffer capable of storing at least +point to a buffer capable of storing at least .Dv PATH_MAX -characters. +characters, or be +.Dv NULL . .Pp The .Fn realpath @@ -82,13 +83,22 @@ The function returns .Fa resolved_path on success. +If the function was supplied +.Dv NULL +as +.Fa resolved_path , +and operation did not cause errors, the returned value is +a null-terminated string in a buffer allocated by a call to +.Fn malloc 3 . If an error occurs, .Fn realpath returns .Dv NULL , -and +and if .Fa resolved_path -contains the pathname which caused the problem. +is not +.Dv NULL , +the array that it points to contains the pathname which caused the problem. .Sh ERRORS The function .Fn realpath @@ -99,6 +109,18 @@ for any of the errors specified for the library functions .Xr readlink 2 and .Xr getcwd 3 . +.Sh SEE ALSO +.Xr getcwd 3 +.\" .Sh STANDARDS +.\" The +.\" .Fn realpath +.\" function conforms to +.\" .St -p1003.1-2001 . +.Sh HISTORY +The +.Fn realpath +function first appeared in +.Bx 4.4 . .Sh CAVEATS This implementation of .Fn realpath @@ -111,10 +133,3 @@ under certain circumstances, return a relative .Fa resolved_path when given a relative .Fa pathname . -.Sh "SEE ALSO" -.Xr getcwd 3 -.Sh HISTORY -The -.Fn realpath -function first appeared in -.Bx 4.4 . diff --git a/lib/libc/stdlib/realpath.c b/lib/libc/stdlib/realpath.c index 3082f5f..66bb8da 100644 --- a/lib/libc/stdlib/realpath.c +++ b/lib/libc/stdlib/realpath.c @@ -43,23 +43,36 @@ __FBSDID("$FreeBSD$"); #include "un-namespace.h" /* - * char *realpath(const char *path, char resolved[PATH_MAX]); - * * 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[PATH_MAX]) +realpath(const char * __restrict path, char * __restrict resolved) { struct stat sb; char *p, *q, *s; size_t left_len, resolved_len; unsigned symlinks; - int serrno, slen; + int m, serrno, slen; char left[PATH_MAX], next_token[PATH_MAX], symlink[PATH_MAX]; + if (path == NULL) { + errno = EINVAL; + return (NULL); + } + if (path[0] == '\0') { + errno = ENOENT; + return (NULL); + } serrno = errno; + if (resolved == NULL) { + resolved = malloc(PATH_MAX); + if (resolved == NULL) + return (NULL); + m = 1; + } else + m = 0; symlinks = 0; if (path[0] == '/') { resolved[0] = '/'; @@ -70,13 +83,20 @@ realpath(const char *path, char resolved[PATH_MAX]) left_len = strlcpy(left, path + 1, sizeof(left)); } else { if (getcwd(resolved, PATH_MAX) == NULL) { - strlcpy(resolved, ".", PATH_MAX); + if (m) + free(resolved); + else { + resolved[0] = '.'; + resolved[1] = '\0'; + } return (NULL); } resolved_len = strlen(resolved); left_len = strlcpy(left, path, sizeof(left)); } if (left_len >= sizeof(left) || resolved_len >= PATH_MAX) { + if (m) + free(resolved); errno = ENAMETOOLONG; return (NULL); } @@ -92,6 +112,8 @@ realpath(const char *path, char resolved[PATH_MAX]) p = strchr(left, '/'); s = p ? p : left + left_len; if (s - left >= sizeof(next_token)) { + if (m) + free(resolved); errno = ENAMETOOLONG; return (NULL); } @@ -102,6 +124,8 @@ realpath(const char *path, char resolved[PATH_MAX]) memmove(left, s + 1, left_len + 1); if (resolved[resolved_len - 1] != '/') { if (resolved_len + 1 >= PATH_MAX) { + if (m) + free(resolved); errno = ENAMETOOLONG; return (NULL); } @@ -133,6 +157,8 @@ realpath(const char *path, char resolved[PATH_MAX]) */ resolved_len = strlcat(resolved, next_token, PATH_MAX); if (resolved_len >= PATH_MAX) { + if (m) + free(resolved); errno = ENAMETOOLONG; return (NULL); } @@ -141,16 +167,23 @@ realpath(const char *path, char resolved[PATH_MAX]) errno = serrno; return (resolved); } + if (m) + free(resolved); return (NULL); } if (S_ISLNK(sb.st_mode)) { if (symlinks++ > MAXSYMLINKS) { + if (m) + free(resolved); errno = ELOOP; return (NULL); } slen = readlink(resolved, symlink, sizeof(symlink) - 1); - if (slen < 0) + if (slen < 0) { + if (m) + free(resolved); return (NULL); + } symlink[slen] = '\0'; if (symlink[0] == '/') { resolved[1] = 0; @@ -171,6 +204,8 @@ realpath(const char *path, char resolved[PATH_MAX]) if (p != NULL) { if (symlink[slen - 1] != '/') { if (slen + 1 >= sizeof(symlink)) { + if (m) + free(resolved); errno = ENAMETOOLONG; return (NULL); } @@ -179,6 +214,8 @@ realpath(const char *path, char resolved[PATH_MAX]) } left_len = strlcat(symlink, left, sizeof(left)); if (left_len >= sizeof(left)) { + if (m) + free(resolved); errno = ENAMETOOLONG; return (NULL); } diff --git a/lib/libc/stdlib/strtod.3 b/lib/libc/stdlib/strtod.3 index ec8ad51..e19e5fe 100644 --- a/lib/libc/stdlib/strtod.3 +++ b/lib/libc/stdlib/strtod.3 @@ -32,7 +32,7 @@ .\" @(#)strtod.3 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd March 2, 2003 +.Dd May 11, 2010 .Dt STRTOD 3 .Os .Sh NAME @@ -169,12 +169,10 @@ The .Fn strtod function conforms to -.St -isoC-99 , -with the exception of the bug noted below. +.St -isoC-99 . .Sh AUTHORS The author of this software is .An David M. Gay . -.Pp .Bd -literal Copyright (c) 1998 by Lucent Technologies All Rights Reserved diff --git a/lib/libc/stdlib/strtonum.3 b/lib/libc/stdlib/strtonum.3 index 90f0b57..b83aadd 100644 --- a/lib/libc/stdlib/strtonum.3 +++ b/lib/libc/stdlib/strtonum.3 @@ -12,7 +12,7 @@ .\" ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF .\" OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. .\" -.\" $OpenBSD: strtonum.3,v 1.12 2005/10/26 11:37:58 jmc Exp $ +.\" $OpenBSD: strtonum.3,v 1.13 2006/04/25 05:15:42 tedu Exp $ .\" $FreeBSD$ .\" .Dd April 29, 2004 @@ -23,7 +23,6 @@ .Nd "reliably convert string value to an integer" .Sh SYNOPSIS .In stdlib.h -.In limits.h .Ft long long .Fo strtonum .Fa "const char *nptr" diff --git a/lib/libc/stdtime/strptime.c b/lib/libc/stdtime/strptime.c index 51d41ed..401350e 100644 --- a/lib/libc/stdtime/strptime.c +++ b/lib/libc/stdtime/strptime.c @@ -408,6 +408,14 @@ label: if (strncasecmp(buf, tptr->month[i], len) == 0) break; + } + } + /* + * Try the abbreviated month name if the full name + * wasn't found and Oalternative was not requested. + */ + if (i == asizeof(tptr->month) && !Oalternative) { + for (i = 0; i < asizeof(tptr->month); i++) { len = strlen(tptr->mon[i]); if (strncasecmp(buf, tptr->mon[i], len) == 0) diff --git a/lib/libc/string/Makefile.inc b/lib/libc/string/Makefile.inc index b0a1899..3673a41 100644 --- a/lib/libc/string/Makefile.inc +++ b/lib/libc/string/Makefile.inc @@ -1,7 +1,7 @@ # @(#)Makefile.inc 8.1 (Berkeley) 6/4/93 # $FreeBSD$ -.PATH: ${.CURDIR}/${MACHINE_ARCH}/string ${.CURDIR}/string +.PATH: ${.CURDIR}/${LIBC_ARCH}/string ${.CURDIR}/string CFLAGS+= -I${.CURDIR}/locale @@ -26,9 +26,7 @@ SYM_MAPS+= ${.CURDIR}/string/Symbol.map # machine-dependent string sources -.if exists(${.CURDIR}/${MACHINE_ARCH}/string/Makefile.inc) -.include "${.CURDIR}/${MACHINE_ARCH}/string/Makefile.inc" -.endif +.sinclude "${.CURDIR}/${LIBC_ARCH}/string/Makefile.inc" MAN+= 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 strcasecmp.3 strcat.3 \ diff --git a/lib/libc/string/ffs.3 b/lib/libc/string/ffs.3 index acb1ac8..bf6f5f5 100644 --- a/lib/libc/string/ffs.3 +++ b/lib/libc/string/ffs.3 @@ -30,7 +30,7 @@ .\" @(#)ffs.3 8.2 (Berkeley) 4/19/94 .\" $FreeBSD$ .\" -.Dd October 26, 2008 +.Dd May 3, 2011 .Dt FFS 3 .Os .Sh NAME @@ -50,8 +50,8 @@ .Ft int .Fn ffsl "long value" .Ft int -.Ft int .Fn ffsll "long long value" +.Ft int .Fn fls "int value" .Ft int .Fn flsl "long value" diff --git a/lib/libc/string/index.3 b/lib/libc/string/index.3 index 34bd9d6..25f6f65 100644 --- a/lib/libc/string/index.3 +++ b/lib/libc/string/index.3 @@ -30,7 +30,7 @@ .\" @(#)index.3 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd June 4, 1993 +.Dd March 20, 2011 .Dt INDEX 3 .Os .Sh NAME @@ -45,6 +45,17 @@ .Ft "char *" .Fn rindex "const char *s" "int c" .Sh DESCRIPTION +.Bf -symbolic +The +.Fn index +and +.Fn rindex +functions have been deprecated in favor of +.Xr strchr 3 +and +.Xr strrchr 3 . +.Ef +.Pp The .Fn index function @@ -100,3 +111,5 @@ before they were moved to for .St -p1003.1-2001 compliance. +The functions are not specified by +.St -p1003.1-2008 . diff --git a/lib/libc/string/strcat.3 b/lib/libc/string/strcat.3 index 4c9fec9..dfa55a4 100644 --- a/lib/libc/string/strcat.3 +++ b/lib/libc/string/strcat.3 @@ -80,6 +80,23 @@ and functions return the pointer .Fa s . +.Sh SEE ALSO +.Xr bcopy 3 , +.Xr memccpy 3 , +.Xr memcpy 3 , +.Xr memmove 3 , +.Xr strcpy 3 , +.Xr strlcat 3 , +.Xr strlcpy 3 , +.Xr wcscat 3 +.Sh STANDARDS +The +.Fn strcat +and +.Fn strncat +functions +conform to +.St -isoC . .Sh SECURITY CONSIDERATIONS The .Fn strcat @@ -138,20 +155,3 @@ foo(const char *arbitrary_string) #endif } .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 , -.Xr wcscat 3 -.Sh STANDARDS -The -.Fn strcat -and -.Fn strncat -functions -conform to -.St -isoC . diff --git a/lib/libc/string/strcpy.3 b/lib/libc/string/strcpy.3 index 157abcc..395e2f9 100644 --- a/lib/libc/string/strcpy.3 +++ b/lib/libc/string/strcpy.3 @@ -174,16 +174,6 @@ Note that because .Xr strlcpy 3 is not defined in any standards, it should only be used when portability is not a concern. -.Sh SECURITY CONSIDERATIONS -The -.Fn strcpy -function is easily misused in a manner which enables malicious users -to arbitrarily change a running program's functionality through a -buffer overflow attack. -(See -the FSA -and -.Sx EXAMPLES . ) .Sh SEE ALSO .Xr bcopy 3 , .Xr memccpy 3 , @@ -214,3 +204,13 @@ and .Fn stpncpy was added in .Fx 8.0 . +.Sh SECURITY CONSIDERATIONS +The +.Fn strcpy +function is easily misused in a manner which enables malicious users +to arbitrarily change a running program's functionality through a +buffer overflow attack. +(See +the FSA +and +.Sx EXAMPLES . ) diff --git a/lib/libc/string/strerror.3 b/lib/libc/string/strerror.3 index 2d6d206..0ec6cb0 100644 --- a/lib/libc/string/strerror.3 +++ b/lib/libc/string/strerror.3 @@ -32,7 +32,7 @@ .\" @(#)strerror.3 8.1 (Berkeley) 6/9/93 .\" $FreeBSD$ .\" -.Dd October 12, 2004 +.Dd April 5, 2011 .Dt STRERROR 3 .Os .Sh NAME @@ -114,6 +114,9 @@ the range 0 < .Fa errnum < .Fa sys_nerr . +The number 0 is also recognized, although applications that take advantage of +this are likely to use unspecified values of +.Va errno . .Pp If insufficient storage is provided in .Fa strerrbuf diff --git a/lib/libc/string/strerror.c b/lib/libc/string/strerror.c index 890ed21..57d253d 100644 --- a/lib/libc/string/strerror.c +++ b/lib/libc/string/strerror.c @@ -87,7 +87,7 @@ strerror_r(int errnum, char *strerrbuf, size_t buflen) catd = catopen("libc", NL_CAT_LOCALE); #endif - if (errnum < 1 || errnum >= sys_nerr) { + if (errnum < 0 || errnum >= sys_nerr) { errstr(errnum, #if defined(NLS) catgets(catd, 1, 0xffff, UPREFIX), diff --git a/lib/libc/string/strlen.c b/lib/libc/string/strlen.c index 860a988..2bc1f2b 100644 --- a/lib/libc/string/strlen.c +++ b/lib/libc/string/strlen.c @@ -1,5 +1,5 @@ /*- - * Copyright (c) 2009 Xin LI <delphij@FreeBSD.org> + * Copyright (c) 2009, 2010 Xin LI <delphij@FreeBSD.org> * All rights reserved. * * Redistribution and use in source and binary forms, with or without @@ -43,15 +43,17 @@ __FBSDID("$FreeBSD$"); * ((x - 0x01....01) & ~x & 0x80....80) * * would evaluate to a non-zero value iff any of the bytes in the - * original word is zero. However, we can further reduce ~1/3 of - * time if we consider that strlen() usually operate on 7-bit ASCII - * by employing the following expression, which allows false positive - * when high bit of 1 and use the tail case to catch these case: + * original word is zero. * - * ((x - 0x01....01) & 0x80....80) + * On multi-issue processors, we can divide the above expression into: + * a) (x - 0x01....01) + * b) (~x & 0x80....80) + * c) a & b * - * This is more than 5.2 times as fast as the raw implementation on - * Intel T7300 under long mode for strings longer than word length. + * Where, a) and b) can be partially computed in parallel. + * + * The algorithm above is found on "Hacker's Delight" by + * Henry S. Warren, Jr. */ /* Magic numbers for the algorithm */ @@ -82,29 +84,47 @@ strlen(const char *str) { const char *p; const unsigned long *lp; + long va, vb; - /* Skip the first few bytes until we have an aligned p */ - for (p = str; (uintptr_t)p & LONGPTR_MASK; p++) - if (*p == '\0') - return (p - str); + /* + * Before trying the hard (unaligned byte-by-byte access) way + * to figure out whether there is a nul character, try to see + * if there is a nul character is within this accessible word + * first. + * + * p and (p & ~LONGPTR_MASK) must be equally accessible since + * they always fall in the same memory page, as long as page + * boundaries is integral multiple of word size. + */ + lp = (const unsigned long *)((uintptr_t)str & ~LONGPTR_MASK); + va = (*lp - mask01); + vb = ((~*lp) & mask80); + lp++; + if (va & vb) + /* Check if we have \0 in the first part */ + for (p = str; p < (const char *)lp; p++) + if (*p == '\0') + return (p - str); /* Scan the rest of the string using word sized operation */ - for (lp = (const unsigned long *)p; ; lp++) - if ((*lp - mask01) & mask80) { - p = (const char *)(lp); - testbyte(0); - testbyte(1); - testbyte(2); - testbyte(3); + for (; ; lp++) { + va = (*lp - mask01); + vb = ((~*lp) & mask80); + if (va & vb) { + p = (const char *)(lp); + testbyte(0); + testbyte(1); + testbyte(2); + testbyte(3); #if (LONG_BIT >= 64) - testbyte(4); - testbyte(5); - testbyte(6); - testbyte(7); + testbyte(4); + testbyte(5); + testbyte(6); + testbyte(7); #endif - } + } + } /* NOTREACHED */ return (0); } - diff --git a/lib/libc/sys/Makefile.inc b/lib/libc/sys/Makefile.inc index 1915c55..008180a 100644 --- a/lib/libc/sys/Makefile.inc +++ b/lib/libc/sys/Makefile.inc @@ -2,7 +2,7 @@ # $FreeBSD$ # sys sources -.PATH: ${.CURDIR}/${MACHINE_ARCH}/sys ${.CURDIR}/sys +.PATH: ${.CURDIR}/${LIBC_ARCH}/sys ${.CURDIR}/sys # Include the generated makefile containing the *complete* list # of syscall names in MIASM. @@ -13,16 +13,20 @@ # MDASM names override the default syscall names in MIASM. # NOASM will prevent the default syscall code from being generated. # -.if exists(${.CURDIR}/${MACHINE_ARCH}/sys/Makefile.inc) -.include "${.CURDIR}/${MACHINE_ARCH}/sys/Makefile.inc" -.endif +.sinclude "${.CURDIR}/${LIBC_ARCH}/sys/Makefile.inc" # Sources common to both syscall interfaces: -SRCS+= stack_protector.c __error.c +SRCS+= stack_protector.c stack_protector_compat.c __error.c .if !defined(WITHOUT_SYSCALL_COMPAT) -SRCS+= fcntl.c ftruncate.c lseek.c mmap.c pread.c pwrite.c truncate.c +SYSCALL_COMPAT_SRCS= fcntl.c ftruncate.c lseek.c mmap.c pread.c \ + pwrite.c truncate.c +SRCS+= ${SYSCALL_COMPAT_SRCS} +NOASM+= ${SYSCALL_COMPAT_SRCS:S/.c/.o/} PSEUDO+= _fcntl.o .endif +SRCS+= sigwait.c +NOASM+= sigwait.o +PSEUDO+= _sigwait.o # Add machine dependent asm sources: SRCS+=${MDASM} @@ -52,26 +56,35 @@ SYM_MAPS+= ${.CURDIR}/sys/Symbol.map # Generated files CLEANFILES+= ${SASM} ${SPSEUDO} +.if ${MACHINE_CPUARCH} == "amd64" || ${MACHINE_CPUARCH} == "i386" || \ + ${MACHINE_CPUARCH} == "powerpc" +NOTE_GNU_STACK='\t.section .note.GNU-stack,"",%%progbits\n' +.else +NOTE_GNU_STACK='' +.endif + ${SASM}: printf '#include "compat.h"\n' > ${.TARGET} printf '#include "SYS.h"\nRSYSCALL(${.PREFIX})\n' >> ${.TARGET} + printf ${NOTE_GNU_STACK} >>${.TARGET} ${SPSEUDO}: printf '#include "compat.h"\n' > ${.TARGET} printf '#include "SYS.h"\nPSEUDO(${.PREFIX:S/_//})\n' \ >> ${.TARGET} + printf ${NOTE_GNU_STACK} >>${.TARGET} MAN+= abort2.2 accept.2 access.2 acct.2 adjtime.2 \ aio_cancel.2 aio_error.2 aio_read.2 aio_return.2 \ aio_suspend.2 aio_waitcomplete.2 aio_write.2 \ - bind.2 brk.2 chdir.2 chflags.2 \ + bind.2 brk.2 cap_enter.2 chdir.2 chflags.2 \ chmod.2 chown.2 chroot.2 clock_gettime.2 close.2 closefrom.2 \ connect.2 cpuset.2 cpuset_getaffinity.2 dup.2 execve.2 _exit.2 \ extattr_get_file.2 fcntl.2 fhopen.2 flock.2 fork.2 fsync.2 \ getdirentries.2 getdtablesize.2 \ getfh.2 getfsstat.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 \ + getloginclass.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 jail.2 kenv.2 kill.2 \ kldfind.2 kldfirstmod.2 kldload.2 kldnext.2 kldstat.2 kldsym.2 \ @@ -83,7 +96,7 @@ MAN+= abort2.2 accept.2 access.2 acct.2 adjtime.2 \ mq_setattr.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 poll.2 posix_openpt.2 profil.2 \ + pathconf.2 pipe.2 poll.2 posix_fallocate.2 posix_openpt.2 profil.2 \ pselect.2 ptrace.2 quotactl.2 \ read.2 readlink.2 reboot.2 recv.2 rename.2 revoke.2 rfork.2 rmdir.2 \ rtprio.2 @@ -105,6 +118,7 @@ MAN+= sctp_generic_recvmsg.2 sctp_generic_sendmsg.2 sctp_peeloff.2 \ MLINKS+=access.2 eaccess.2 access.2 faccessat.2 MLINKS+=brk.2 sbrk.2 +MLINKS+=cap_enter.2 cap_getmode.2 MLINKS+=chdir.2 fchdir.2 MLINKS+=chflags.2 fchflags.2 chflags.2 lchflags.2 MLINKS+=chmod.2 fchmod.2 chmod.2 fchmodat.2 chmod.2 lchmod.2 @@ -133,6 +147,7 @@ MLINKS+=getgid.2 getegid.2 MLINKS+=getitimer.2 setitimer.2 MLINKS+=getlogin.2 getlogin_r.3 MLINKS+=getlogin.2 setlogin.2 +MLINKS+=getloginclass.2 setloginclass.2 MLINKS+=getpgrp.2 getpgid.2 MLINKS+=getpid.2 getppid.2 MLINKS+=getpriority.2 setpriority.2 diff --git a/lib/libc/sys/Symbol.map b/lib/libc/sys/Symbol.map index ce6f32a..cd31f24 100644 --- a/lib/libc/sys/Symbol.map +++ b/lib/libc/sys/Symbol.map @@ -360,6 +360,19 @@ FBSD_1.1 { unlinkat; }; +FBSD_1.2 { + cap_enter; + cap_getmode; + getloginclass; + posix_fallocate; + rctl_get_racct; + rctl_get_rules; + rctl_get_limits; + rctl_add_rule; + rctl_remove_rule; + setloginclass; +}; + FBSDprivate_1.0 { ___acl_aclcheck_fd; __sys___acl_aclcheck_fd; @@ -919,6 +932,7 @@ FBSDprivate_1.0 { _sigtimedwait; __sys_sigtimedwait; _sigwait; + __sigwait; __sys_sigwait; _sigwaitinfo; __sys_sigwaitinfo; diff --git a/lib/libc/sys/access.2 b/lib/libc/sys/access.2 index 0cd3c6f..65b8fb6 100644 --- a/lib/libc/sys/access.2 +++ b/lib/libc/sys/access.2 @@ -188,6 +188,27 @@ is neither .Dv AT_FDCWD nor a file descriptor associated with a directory. .El +.Sh SEE ALSO +.Xr chmod 2 , +.Xr intro 2 , +.Xr stat 2 +.Sh STANDARDS +The +.Fn access +system call is expected to conform to +.St -p1003.1-90 . +The +.Fn faccessat +system call follows The Open Group Extended API Set 2 specification. +.Sh HISTORY +The +.Fn access +function appeared in +.At v7 . +The +.Fn faccessat +system call appeared in +.Fx 8.0 . .Sh SECURITY CONSIDERATIONS The .Fn access @@ -212,24 +233,3 @@ of the st_mode bits that the application might not understand -- e.g. in the case of AFS). It also allows a cheaper file existence test than .Xr stat 2 . -.Sh SEE ALSO -.Xr chmod 2 , -.Xr intro 2 , -.Xr stat 2 -.Sh STANDARDS -The -.Fn access -system call is expected to conform to -.St -p1003.1-90 . -The -.Fn faccessat -system call follows The Open Group Extended API Set 2 specification. -.Sh HISTORY -The -.Fn access -function appeared in -.At v7 . -The -.Fn faccessat -system call appeared in -.Fx 8.0 . diff --git a/lib/libc/sys/aio_read.2 b/lib/libc/sys/aio_read.2 index 2c78040..ddf4f76 100644 --- a/lib/libc/sys/aio_read.2 +++ b/lib/libc/sys/aio_read.2 @@ -136,7 +136,6 @@ system call must be called, and will return -1, and must be called to determine the actual value that would have been returned in .Va errno . -.Pp .Bl -tag -width Er .It Bq Er EBADF The diff --git a/lib/libc/sys/aio_write.2 b/lib/libc/sys/aio_write.2 index dd1e0f5..291fd71 100644 --- a/lib/libc/sys/aio_write.2 +++ b/lib/libc/sys/aio_write.2 @@ -140,7 +140,6 @@ system call must be called, and will return -1, and must be called to determine the actual value that would have been returned in .Va errno . -.Pp .Bl -tag -width Er .It Bq Er EBADF The diff --git a/lib/libc/sys/cap_enter.2 b/lib/libc/sys/cap_enter.2 new file mode 100644 index 0000000..83b4739 --- /dev/null +++ b/lib/libc/sys/cap_enter.2 @@ -0,0 +1,101 @@ +.\" +.\" Copyright (c) 2008-2009 Robert N. M. Watson +.\" All rights reserved. +.\" +.\" This software was developed at the University of Cambridge Computer +.\" Laboratory with support from a grant from Google, 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 AUTHOR AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (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$ +.\" +.Dd June 11, 2009 +.Dt CAP_ENTER 2 +.Os +.Sh NAME +.Nm cap_enter , +.Nm cap_getmode +.Nd Capability mode system calls +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In sys/capability.h +.Ft int +.Fn cap_enter "void" +.Ft int +.Fn cap_getmode "u_int *modep" +.Sh DESCRIPTION +.Fn cap_enter +places the current process into capability mode, a mode of execution in which +processes may only issue system calls operating on file descriptors or +reading limited global system state. +Access to global name spaces, such as file system or IPC name spaces, is +prevented. +If the process is already in a capability mode sandbox, the system call is a +no-op. +Future process descendants create with +.Xr fork 2 +or +.Xr pdfork 2 +will be placed in capability mode from inception. +.Pp +When combined with capabilities created with +.Xr cap_new 2 , +.Fn cap_enter +may be used to create kernel-enforced sandboxes in which +appropriately-crafted applications or application components may be run. +.Pp +.Fn cap_getmode +returns a flag indicating whether or not the process is in a capability mode +sandbox. +.Sh CAVEAT +Creating effecive process sandboxes is a tricky process that involves +identifying the least possible rights required by the process and then +passing those rights into the process in a safe manner. +See the CAVEAT +section of +.Xr cap_new 2 +for why this is particularly tricky with UNIX file descriptors as the +canonical representation of a right. +Consumers of +.Fn cap_enter +should also be aware of other inherited rights, such as access to VM +resources, memory contents, and other process properties that should be +considered. +It is advisable to use +.Xr fexecve 2 +to create a runtime environment inside the sandbox that has as few implicitly +acquired rights as possible. +.Sh RETURN VALUES +.Rv -std cap_enter cap_getmode +.Sh SEE ALSO +.Xr cap_new 2 , +.Xr fexecve 2 +.Sh HISTORY +Support for capabilities and capabilities mode was developed as part of the +.Tn TrustedBSD +Project. +.Sh AUTHORS +These functions and the capability facility were created by +.An "Robert N. M. Watson" +at the University of Cambridge Computer Laboratory with support from a grant +from Google, Inc. diff --git a/lib/libc/sys/chflags.2 b/lib/libc/sys/chflags.2 index 7780427..79f2fe0 100644 --- a/lib/libc/sys/chflags.2 +++ b/lib/libc/sys/chflags.2 @@ -28,7 +28,7 @@ .\" @(#)chflags.2 8.3 (Berkeley) 5/2/95 .\" $FreeBSD$ .\" -.Dd May 16, 2006 +.Dd Oct 29, 2010 .Dt CHFLAGS 2 .Os .Sh NAME @@ -155,7 +155,7 @@ is set and the user is either not the super-user or securelevel is greater than 0. .It Bq Er EPERM A non-super-user tries to set one of -.Dv SF_IMMUTABLE , SF_APPEND , +.Dv SF_ARCHIVED , SF_IMMUTABLE , SF_APPEND , or .Dv SF_NOUNLINK . .It Bq Er EPERM @@ -200,9 +200,13 @@ is set and the user is either not the super-user or securelevel is greater than 0. .It Bq Er EPERM A non-super-user tries to set one of -.Dv SF_IMMUTABLE , SF_APPEND , +.Dv SF_ARCHIVED , SF_IMMUTABLE , SF_APPEND , or .Dv SF_NOUNLINK . +.It Bq Er EPERM +User tries to set or remove the +.Dv SF_SNAPSHOT +flag. .It Bq Er EROFS The file resides on a read-only file system. .It Bq Er EIO diff --git a/lib/libc/sys/chmod.2 b/lib/libc/sys/chmod.2 index 3547aec..997df88e 100644 --- a/lib/libc/sys/chmod.2 +++ b/lib/libc/sys/chmod.2 @@ -161,7 +161,7 @@ The sticky bit may be set by any user on a directory which the user owns or has appropriate permissions. For more details of the properties of the sticky bit, see -.Xr sticky 8 . +.Xr sticky 7 . .Pp If mode ISUID (set UID) is set on a directory, and the MNT_SUIDDIR option was used in the mount of the file system, @@ -289,7 +289,7 @@ nor a file descriptor associated with a directory. .Xr chown 2 , .Xr open 2 , .Xr stat 2 , -.Xr sticky 8 +.Xr sticky 7 .Sh STANDARDS The .Fn chmod diff --git a/lib/libc/sys/clock_gettime.2 b/lib/libc/sys/clock_gettime.2 index a2fa624..583cc8f 100644 --- a/lib/libc/sys/clock_gettime.2 +++ b/lib/libc/sys/clock_gettime.2 @@ -102,7 +102,6 @@ The structure pointed to by is defined in .In sys/timespec.h as: -.Pp .Bd -literal struct timespec { time_t tv_sec; /* seconds */ diff --git a/lib/libc/sys/connect.2 b/lib/libc/sys/connect.2 index c673a83..ac019e8 100644 --- a/lib/libc/sys/connect.2 +++ b/lib/libc/sys/connect.2 @@ -28,7 +28,7 @@ .\" @(#)connect.2 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd August 16, 2006 +.Dd September 5, 2010 .Dt CONNECT 2 .Os .Sh NAME @@ -95,6 +95,8 @@ The socket is already connected. Connection establishment timed out without establishing a connection. .It Bq Er ECONNREFUSED The attempt to connect was forcefully rejected. +.It Bq Er ECONNRESET +The connection was reset by the remote host. .It Bq Er ENETUNREACH The network is not reachable from this host. .It Bq Er EHOSTUNREACH diff --git a/lib/libc/sys/cpuset_getaffinity.2 b/lib/libc/sys/cpuset_getaffinity.2 index c8b272f..5c75b92 100644 --- a/lib/libc/sys/cpuset_getaffinity.2 +++ b/lib/libc/sys/cpuset_getaffinity.2 @@ -25,7 +25,7 @@ .\" .\" $FreeBSD$ .\" -.Dd January 8, 2010 +.Dd September 10, 2010 .Dt CPUSET 2 .Os .Sh NAME @@ -121,6 +121,12 @@ The or .Fa which argument was not a valid value. +.It Bq Er EINVAL +The +.Fa mask +argument specified when calling +.Fn cpuset_setaffinity +was not a valid value. .It Bq Er EDEADLK The .Fn cpuset_setaffinity diff --git a/lib/libc/sys/execve.2 b/lib/libc/sys/execve.2 index cdd4197..991495c 100644 --- a/lib/libc/sys/execve.2 +++ b/lib/libc/sys/execve.2 @@ -28,7 +28,7 @@ .\" @(#)execve.2 8.5 (Berkeley) 6/1/94 .\" $FreeBSD$ .\" -.Dd April 10, 2008 +.Dd September 21, 2010 .Dt EXECVE 2 .Os .Sh NAME @@ -189,8 +189,8 @@ the calling process: .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 sigvec 2 , -.Xr sigsetmask 2 +.It signal mask Ta see Xr sigaction 2 , +.Xr sigprocmask 2 .El .Pp When a program is executed as a result of an @@ -256,9 +256,11 @@ 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 ENAMETOOLONG -When invoking an interpreted script, the interpreter name -exceeds +.It Bq Er ENOEXEC +When invoking an interpreted script, the length of the first line, +inclusive of the +.Sy \&#! +prefix and terminating newline, exceeds .Dv MAXSHELLCMDLEN characters. .It Bq Er ENOENT @@ -313,30 +315,6 @@ The .Fa fd argument is not a valid file descriptor open for executing. .El -.Sh CAVEATS -If a program is -.Em setuid -to a non-super-user, but is executed when -the real -.Em uid -is ``root'', then the program has some of the powers -of a super-user as well. -.Pp -When executing an interpreted program through -.Fn fexecve , -kernel supplies -.Pa /dev/fd/n -as a second argument to the interpreter, -where -.Ar n -is the file descriptor passed in the -.Fa fd -argument to -.Fn fexecve . -For this construction to work correctly, the -.Xr fdescfs 5 -filesystem shall be mounted on -.Pa /dev/fd . .Sh SEE ALSO .Xr ktrace 1 , .Xr _exit 2 , @@ -373,3 +351,27 @@ The .Fn fexecve system call appeared in .Fx 8.0 . +.Sh CAVEATS +If a program is +.Em setuid +to a non-super-user, but is executed when +the real +.Em uid +is ``root'', then the program has some of the powers +of a super-user as well. +.Pp +When executing an interpreted program through +.Fn fexecve , +kernel supplies +.Pa /dev/fd/n +as a second argument to the interpreter, +where +.Ar n +is the file descriptor passed in the +.Fa fd +argument to +.Fn fexecve . +For this construction to work correctly, the +.Xr fdescfs 5 +filesystem shall be mounted on +.Pa /dev/fd . diff --git a/lib/libc/sys/fcntl.2 b/lib/libc/sys/fcntl.2 index 250cef4..a801b60 100644 --- a/lib/libc/sys/fcntl.2 +++ b/lib/libc/sys/fcntl.2 @@ -618,7 +618,7 @@ for the reasons as stated in .Xr flock 2 , .Xr getdtablesize 2 , .Xr open 2 , -.Xr sigvec 2 , +.Xr sigaction 2 , .Xr lockf 3 , .Xr tcgetpgrp 3 , .Xr tcsetpgrp 3 diff --git a/lib/libc/sys/flock.2 b/lib/libc/sys/flock.2 index 4ad8525..93f1f66 100644 --- a/lib/libc/sys/flock.2 +++ b/lib/libc/sys/flock.2 @@ -38,10 +38,10 @@ .Lb libc .Sh SYNOPSIS .In sys/file.h -.Fd "#define LOCK_SH 0x01 /* shared file lock */" -.Fd "#define LOCK_EX 0x02 /* exclusive file lock */" -.Fd "#define LOCK_NB 0x04 /* do not block when locking */" -.Fd "#define LOCK_UN 0x08 /* unlock file */" +.Fd "#define LOCK_SH 0x01 /* shared file lock */" +.Fd "#define LOCK_EX 0x02 /* exclusive file lock */" +.Fd "#define LOCK_NB 0x04 /* do not block when locking */" +.Fd "#define LOCK_UN 0x08 /* unlock file */" .Ft int .Fn flock "int fd" "int operation" .Sh DESCRIPTION diff --git a/lib/libc/sys/getfh.2 b/lib/libc/sys/getfh.2 index 1488196..b44d4af 100644 --- a/lib/libc/sys/getfh.2 +++ b/lib/libc/sys/getfh.2 @@ -28,7 +28,7 @@ .\" @(#)getfh.2 8.1 (Berkeley) 6/9/93 .\" $FreeBSD$ .\" -.Dd April 6, 2004 +.Dd April 14, 2011 .Dt GETFH 2 .Os .Sh NAME @@ -69,7 +69,7 @@ These system calls are restricted to the superuser. The .Fn getfh and -.Fn lgetfgh +.Fn lgetfh system calls fail if one or more of the following are true: .Bl -tag -width Er @@ -104,6 +104,10 @@ An .Tn I/O error occurred while reading from or writing to the file system. .El +.Sh SEE ALSO +.Xr fhopen 2 , +.Xr open 2 , +.Xr stat 2 .Sh HISTORY The .Fn getfh diff --git a/lib/libc/sys/getgroups.2 b/lib/libc/sys/getgroups.2 index 4fd8fee..66238a1 100644 --- a/lib/libc/sys/getgroups.2 +++ b/lib/libc/sys/getgroups.2 @@ -28,7 +28,7 @@ .\" @(#)getgroups.2 8.2 (Berkeley) 4/16/94 .\" $FreeBSD$ .\" -.Dd March 5, 1999 +.Dd January 21, 2011 .Dt GETGROUPS 2 .Os .Sh NAME @@ -37,7 +37,6 @@ .Sh LIBRARY .Lb libc .Sh SYNOPSIS -.In sys/types.h .In unistd.h .Ft int .Fn getgroups "int gidsetlen" "gid_t *gidset" @@ -66,6 +65,12 @@ is zero, returns the number of supplementary group IDs associated with the calling process without modifying the array pointed to by .Fa gidset . +.Pp +The value of +.Dv {NGROUPS_MAX} +should be obtained using +.Xr sysconf 3 +to avoid hard-coding it into the executable. .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 @@ -88,7 +93,8 @@ an invalid address. .El .Sh SEE ALSO .Xr setgroups 2 , -.Xr initgroups 3 +.Xr initgroups 3 , +.Xr sysconf 3 .Sh STANDARDS The .Fn getgroups diff --git a/lib/libc/sys/getitimer.2 b/lib/libc/sys/getitimer.2 index 260f8f0..539dea6 100644 --- a/lib/libc/sys/getitimer.2 +++ b/lib/libc/sys/getitimer.2 @@ -39,9 +39,9 @@ .Lb libc .Sh SYNOPSIS .In sys/time.h -.Fd "#define ITIMER_REAL 0" -.Fd "#define ITIMER_VIRTUAL 1" -.Fd "#define ITIMER_PROF 2" +.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 @@ -171,7 +171,7 @@ to be handled. .Sh SEE ALSO .Xr gettimeofday 2 , .Xr select 2 , -.Xr sigvec 2 , +.Xr sigaction 2 , .Xr clocks 7 .Sh HISTORY The diff --git a/lib/libc/sys/getloginclass.2 b/lib/libc/sys/getloginclass.2 new file mode 100644 index 0000000..6817330 --- /dev/null +++ b/lib/libc/sys/getloginclass.2 @@ -0,0 +1,97 @@ +.\"- +.\" Copyright (c) 2011 Edward Tomasz Napierala +.\" All rights reserved. +.\" +.\" Redistribution and use in source and binary forms, with or without +.\" modification, are permitted provided that the following conditions +.\" are met: +.\" 1. Redistributions of source code must retain the above copyright +.\" notice, this list of conditions and the following disclaimer. +.\" 2. Redistributions in binary form must reproduce the above copyright +.\" notice, this list of conditions and the following disclaimer in the +.\" documentation and/or other materials provided with the distribution. +.\" +.\" THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND +.\" ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +.\" IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE +.\" ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE +.\" FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +.\" DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS +.\" OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) +.\" HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT +.\" LIABILITY, OR TORT (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$ +.\" +.Dd March 6, 2011 +.Dt GETLOGINCLASS 2 +.Os +.Sh NAME +.Nm getloginclass , +.Nm setloginclass +.Nd get/set login class +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In unistd.h +.Ft int +.Fn getloginclass "char *name" "size_t len" +.Ft int +.Fn setloginclass "const char *name" +.Sh DESCRIPTION +The +.Fn getloginclass +routine returns the login class name associated with the calling process, +as previously set by +.Fn setloginclass . +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 +The +.Fn setloginclass +system call sets the login class of the calling process to +.Fa name . +This system 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). +Processes inherit login class from their parents. +.Sh RETURN VALUES +.Rv -std +.Sh ERRORS +The following errors may be returned by these calls: +.Bl -tag -width Er +.It Bq Er EFAULT +The +.Fa name +argument gave an invalid address. +.It Bq Er EINVAL +The +.Fa name +argument pointed to a string that was too long. +Login class names are limited to +.Dv MAXLOGNAME +(from +.In sys/param.h ) +characters, currently 17 including null. +.It Bq Er EPERM +The caller tried to set the login class and was not the super-user. +.It Bq Er ENAMETOOLONG +The size of the buffer is smaller than the result to be returned. +.El +.Sh SEE ALSO +.Xr setusercontext 3 +.Sh HISTORY +The +.Fn getloginclass +and +.Fn setloginclass +system calls first appeared in +.Fx 9.0 . diff --git a/lib/libc/sys/getpriority.2 b/lib/libc/sys/getpriority.2 index 28d1f14..ae70f5f 100644 --- a/lib/libc/sys/getpriority.2 +++ b/lib/libc/sys/getpriority.2 @@ -129,10 +129,10 @@ or .Dv PRIO_USER . .El .Pp -.Bl -tag -width Er 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. diff --git a/lib/libc/sys/getrlimit.2 b/lib/libc/sys/getrlimit.2 index 48feea0..35198bc 100644 --- a/lib/libc/sys/getrlimit.2 +++ b/lib/libc/sys/getrlimit.2 @@ -193,7 +193,7 @@ raised the maximum limit value, and the caller is not the super-user. .Xr quota 1 , .Xr quotactl 2 , .Xr sigaltstack 2 , -.Xr sigvec 2 , +.Xr sigaction 2 , .Xr sysctl 3 , .Xr ulimit 3 .Sh HISTORY diff --git a/lib/libc/sys/getrusage.2 b/lib/libc/sys/getrusage.2 index bdf5d45..45ded18 100644 --- a/lib/libc/sys/getrusage.2 +++ b/lib/libc/sys/getrusage.2 @@ -28,7 +28,7 @@ .\" @(#)getrusage.2 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd June 4, 1993 +.Dd May 1, 2010 .Dt GETRUSAGE 2 .Os .Sh NAME @@ -40,8 +40,9 @@ .In sys/types.h .In sys/time.h .In sys/resource.h -.Fd "#define RUSAGE_SELF 0" -.Fd "#define RUSAGE_CHILDREN -1" +.Fd "#define RUSAGE_SELF 0" +.Fd "#define RUSAGE_CHILDREN -1" +.Fd "#define RUSAGE_THREAD 1" .Ft int .Fn getrusage "int who" "struct rusage *rusage" .Sh DESCRIPTION @@ -49,11 +50,12 @@ The .Fn getrusage system call returns information describing the resources utilized by the current -process, or all its terminated child processes. +thread, the current process, or all its terminated child processes. The .Fa who argument is either -.Dv RUSAGE_SELF +.Dv RUSAGE_THREAD , +.Dv RUSAGE_SELF , or .Dv RUSAGE_CHILDREN . The buffer to which @@ -175,6 +177,10 @@ The .Fn getrusage system call appeared in .Bx 4.2 . +The +.Dv RUSAGE_THREAD +facility first appeared in +.Fx 8.1 . .Sh BUGS There is no way to obtain information about a child process that has not yet terminated. diff --git a/lib/libc/sys/getsockopt.2 b/lib/libc/sys/getsockopt.2 index d3472d0..7370b6b 100644 --- a/lib/libc/sys/getsockopt.2 +++ b/lib/libc/sys/getsockopt.2 @@ -184,15 +184,18 @@ The following options are recognized in .It Dv SO_LISTENQLIMIT Ta "get backlog limit of the socket (get only)" .It Dv SO_LISTENQLEN Ta "get complete queue length of the socket (get only)" .It Dv SO_LISTENINCQLEN Ta "get incomplete queue length of the socket (get only)" +.It Dv SO_USER_COOKIE Ta "set the 'so_user_cookie' value for the socket (uint32_t, set only)" .El .Pp .Dv SO_DEBUG enables debugging in the underlying protocol modules. +.Pp .Dv SO_REUSEADDR indicates that the rules used in validating addresses supplied in a .Xr bind 2 system call should allow reuse of local addresses. +.Pp .Dv SO_REUSEPORT allows completely duplicate bindings by multiple processes if they all set @@ -200,6 +203,7 @@ if they all set 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. +.Pp .Dv SO_KEEPALIVE enables the periodic transmission of messages on a connected socket. @@ -208,6 +212,7 @@ 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. +.Pp .Dv SO_DONTROUTE indicates that outgoing messages should bypass the standard routing facilities. @@ -244,6 +249,7 @@ The option requests permission to send broadcast datagrams on the socket. Broadcast was a privileged operation in earlier versions of the system. +.Pp With protocols that support out-of-band data, the .Dv SO_OOBINLINE option @@ -256,6 +262,7 @@ calls without the .Dv MSG_OOB flag. Some protocols always behave as if this option is set. +.Pp .Dv SO_SNDBUF and .Dv SO_RCVBUF @@ -285,6 +292,7 @@ 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. +.Pp .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 @@ -317,6 +325,7 @@ 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. +.Pp .Dv SO_RCVTIMEO is an option to set a timeout value for input operations. It accepts a @@ -338,6 +347,15 @@ The value must be from 0 to one less than the number returned from the sysctl .Em net.fibs . .Pp +.Dv SO_USER_COOKIE +can be used to set the uint32_t so_user_cookie field in the socket. +The value is an uint32_t, and can be used in the kernel code that +manipulates traffic related to the socket. +The default value for the field is 0. +As an example, the value can be used as the skipto target or +pipe number in +.Nm ipfw/dummynet . +.Pp .Dv SO_ACCEPTFILTER places an .Xr accept_filter 9 diff --git a/lib/libc/sys/gettimeofday.2 b/lib/libc/sys/gettimeofday.2 index 9ffd0b3..23cc059 100644 --- a/lib/libc/sys/gettimeofday.2 +++ b/lib/libc/sys/gettimeofday.2 @@ -75,7 +75,6 @@ and are defined in .In sys/time.h as: -.Pp .Bd -literal struct timeval { time_t tv_sec; /* seconds */ diff --git a/lib/libc/sys/intro.2 b/lib/libc/sys/intro.2 index e5ff9df..1a22ea2 100644 --- a/lib/libc/sys/intro.2 +++ b/lib/libc/sys/intro.2 @@ -467,6 +467,8 @@ A device or socket encountered an unrecoverable protocol error. .It Er 93 ENOTCAPABLE Em "Capabilities insufficient" . An operation on a capability file descriptor requires greater privilege than the capability allows. +.It Er 94 ECAPMODE Em "Not permitted in capability mode" . +The system call or operation is not permitted for capability mode processes. .El .Sh DEFINITIONS .Bl -tag -width Ds diff --git a/lib/libc/sys/ioctl.2 b/lib/libc/sys/ioctl.2 index 57d50c2..bab7b47 100644 --- a/lib/libc/sys/ioctl.2 +++ b/lib/libc/sys/ioctl.2 @@ -29,7 +29,7 @@ .\" .\" $FreeBSD$ .\" -.Dd July 14, 2007 +.Dd May 11, 2010 .Dt IOCTL 2 .Os .Sh NAME @@ -80,6 +80,30 @@ Macros and defines used in specifying an ioctl .Fa request are located in the file .In sys/ioctl.h . +.Sh GENERIC IOCTLS +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 TCP sockets, these bytes have not yet been acknowledged by the +other side of the connection. +.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. +.El .Sh RETURN VALUES If an error has occurred, a value of -1 is returned and .Va errno diff --git a/lib/libc/sys/jail.2 b/lib/libc/sys/jail.2 index 2e14f0d..bf6218c 100644 --- a/lib/libc/sys/jail.2 +++ b/lib/libc/sys/jail.2 @@ -89,7 +89,7 @@ from the inside of the prison. The .Dq Li jailname pointer is an optional name that can be assigned to the jail -for example for managment purposes. +for example for management purposes. .Pp The .Dq Li ip4s diff --git a/lib/libc/sys/kldstat.2 b/lib/libc/sys/kldstat.2 index eb09a23..7a48296 100644 --- a/lib/libc/sys/kldstat.2 +++ b/lib/libc/sys/kldstat.2 @@ -25,7 +25,7 @@ .\" .\" $FreeBSD$ .\" -.Dd March 3, 1999 +.Dd April 23, 2011 .Dt KLDSTAT 2 .Os .Sh NAME @@ -51,12 +51,11 @@ struct kld_file_stat { char name[MAXPATHLEN]; int refs; int id; - caddr_t address; /* load address */ - size_t size; /* size in bytes */ + caddr_t address; + size_t size; char pathname[MAXPATHLEN]; }; .Ed -.Pp .Bl -tag -width XXXaddress .It version This field is set to the size of the structure mentioned above by the code @@ -77,7 +76,7 @@ The id of the file specified in .It address The load address of the kld file. .It size -The size of the file. +The amount of memory in bytes allocated by the file. .It pathname The full name of the file referred to by .Fa fileid , @@ -129,6 +128,6 @@ The interface first appeared in .Fx 3.0 . .Sh BUGS -The pathname many not be accurate if the file system mounts have +The pathname may not be accurate if the file system mounts have changed since the module was loaded, or if this function is called within a chrooted environment. diff --git a/lib/libc/sys/kldsym.2 b/lib/libc/sys/kldsym.2 index acd6fcd..917a92a 100644 --- a/lib/libc/sys/kldsym.2 +++ b/lib/libc/sys/kldsym.2 @@ -55,7 +55,6 @@ implemented is The .Fa data argument is of the following structure: -.Pp .Bd -literal -offset indent struct kld_sym_lookup { int version; /* sizeof(struct kld_sym_lookup) */ diff --git a/lib/libc/sys/kqueue.2 b/lib/libc/sys/kqueue.2 index 326632d..a1b6177 100644 --- a/lib/libc/sys/kqueue.2 +++ b/lib/libc/sys/kqueue.2 @@ -251,7 +251,6 @@ 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 @@ -445,7 +444,7 @@ contains the events which triggered the filter. .It Dv EVFILT_USER Establishes a user event identified by .Va ident -which is not assosicated with any kernel mechanism but is triggered by +which is not associated with any kernel mechanism but is triggered by user level code. The lower 24 bits of the .Va fflags diff --git a/lib/libc/sys/mknod.2 b/lib/libc/sys/mknod.2 index 0fc8771..a406068 100644 --- a/lib/libc/sys/mknod.2 +++ b/lib/libc/sys/mknod.2 @@ -28,7 +28,7 @@ .\" @(#)mknod.2 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd April 10, 2008 +.Dd January 16, 2011 .Dt MKNOD 2 .Os .Sh NAME @@ -38,7 +38,7 @@ .Sh LIBRARY .Lb libc .Sh SYNOPSIS -.In unistd.h +.In sys/stat.h .Ft int .Fn mknod "const char *path" "mode_t mode" "dev_t dev" .Ft int diff --git a/lib/libc/sys/mlock.2 b/lib/libc/sys/mlock.2 index 0c05b7b..ed9c15a 100644 --- a/lib/libc/sys/mlock.2 +++ b/lib/libc/sys/mlock.2 @@ -28,7 +28,7 @@ .\" @(#)mlock.2 8.2 (Berkeley) 12/11/93 .\" $FreeBSD$ .\" -.Dd August 10, 2004 +.Dd July 27, 2010 .Dt MLOCK 2 .Os .Sh NAME @@ -116,11 +116,12 @@ The caller is not the super-user. .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. +Locking the indicated range would exceed the system 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. +Locking the indicated range would exceed the per-process limit for locked +memory. .El The .Fn munlock diff --git a/lib/libc/sys/mlockall.2 b/lib/libc/sys/mlockall.2 index d09ce27..54ae23e 100644 --- a/lib/libc/sys/mlockall.2 +++ b/lib/libc/sys/mlockall.2 @@ -30,7 +30,7 @@ .\" .\" $FreeBSD$ .\" -.Dd June 12, 1999 +.Dd July 27, 2010 .Dt MLOCKALL 2 .Os .Sh NAME @@ -72,6 +72,8 @@ limit and the per-process .Dv RLIMIT_MEMLOCK resource limit. .Pp +These calls are only available to the super-user. +.Pp The .Fn munlockall call unlocks any locked memory regions in the process address space. diff --git a/lib/libc/sys/mmap.2 b/lib/libc/sys/mmap.2 index 4849973..5e0c226 100644 --- a/lib/libc/sys/mmap.2 +++ b/lib/libc/sys/mmap.2 @@ -28,7 +28,7 @@ .\" @(#)mmap.2 8.4 (Berkeley) 5/11/95 .\" $FreeBSD$ .\" -.Dd November 6, 2009 +.Dd August 28, 2010 .Dt MMAP 2 .Os .Sh NAME @@ -105,7 +105,7 @@ The file descriptor used for creating must be \-1. The .Fa offset -argument is ignored. +argument must be 0. .\".It Dv MAP_FILE .\"Mapped from a regular file or character-special device memory. .It Dv MAP_ANONYMOUS @@ -211,6 +211,19 @@ implements a coherent file system buffer cache. However, it may be used to associate dirty VM pages with file system buffers and thus cause them to be flushed to physical media sooner rather than later. +.It Dv MAP_PREFAULT_READ +Immediately update the calling process's lowest-level virtual address +translation structures, such as its page table, so that every memory +resident page within the region is mapped for read access. +Ordinarily these structures are updated lazily. +The effect of this option is to eliminate any soft faults that would +otherwise occur on the initial read accesses to the region. +Although this option does not preclude +.Fa prot +from including +.Dv PROT_WRITE , +it does not eliminate soft faults on the initial write accesses to the +region. .It Dv MAP_PRIVATE Modifications are private. .It Dv MAP_SHARED @@ -316,6 +329,11 @@ was equal to zero. was specified and the .Fa fd argument was not -1. +.It Bq Er EINVAL +.Dv MAP_ANON +was specified and the +.Fa offset +argument was not 0. .It Bq Er ENODEV .Dv MAP_ANON has not been specified and @@ -328,9 +346,6 @@ was specified and the argument was not available. .Dv MAP_ANON was specified and insufficient memory was available. -The system has reached the per-process mmap limit specified in the -.Va vm.max_proc_mmap -sysctl. .El .Sh SEE ALSO .Xr madvise 2 , diff --git a/lib/libc/sys/modstat.2 b/lib/libc/sys/modstat.2 index 439cce7..5f106b4 100644 --- a/lib/libc/sys/modstat.2 +++ b/lib/libc/sys/modstat.2 @@ -60,7 +60,6 @@ typedef union modspecific { u_long ulongval; } modspecific_t; .Ed -.Pp .Bl -tag -width XXXaddress .It version This field is set to the size of the structure mentioned above by the code diff --git a/lib/libc/sys/mount.2 b/lib/libc/sys/mount.2 index b65c1b6..57ad428 100644 --- a/lib/libc/sys/mount.2 +++ b/lib/libc/sys/mount.2 @@ -107,7 +107,7 @@ This restriction can be removed by setting the .Va vfs.usermount .Xr sysctl 8 variable -to a non-zero value. +to a non-zero value; see the BUGS section for more information. .Pp The following .Fa flags @@ -374,3 +374,10 @@ system call first appeared in .Fx 5.0 . .Sh BUGS Some of the error codes need translation to more obvious messages. +.Pp +Allowing untrusted users to mount arbitrary media, e.g. by enabling +.Va vfs.usermount , +should not be considered safe. +Most file systems in +.Fx +were not built to safeguard against malicious devices. diff --git a/lib/libc/sys/mq_close.2 b/lib/libc/sys/mq_close.2 index de45edd..f9ec062 100644 --- a/lib/libc/sys/mq_close.2 +++ b/lib/libc/sys/mq_close.2 @@ -102,4 +102,4 @@ Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at - http://www.opengroup.org/unix/online.html. +http://www.opengroup.org/unix/online.html. diff --git a/lib/libc/sys/mq_getattr.2 b/lib/libc/sys/mq_getattr.2 index 1403418..77253fc 100644 --- a/lib/libc/sys/mq_getattr.2 +++ b/lib/libc/sys/mq_getattr.2 @@ -124,4 +124,4 @@ Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at - http://www.opengroup.org/unix/online.html. +http://www.opengroup.org/unix/online.html. diff --git a/lib/libc/sys/mq_notify.2 b/lib/libc/sys/mq_notify.2 index 5bed088..1e3a5ad 100644 --- a/lib/libc/sys/mq_notify.2 +++ b/lib/libc/sys/mq_notify.2 @@ -148,4 +148,4 @@ Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at - http://www.opengroup.org/unix/online.html. +http://www.opengroup.org/unix/online.html. diff --git a/lib/libc/sys/mq_open.2 b/lib/libc/sys/mq_open.2 index 3b30423..5acc59b 100644 --- a/lib/libc/sys/mq_open.2 +++ b/lib/libc/sys/mq_open.2 @@ -320,4 +320,4 @@ Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at - http://www.opengroup.org/unix/online.html. +http://www.opengroup.org/unix/online.html. diff --git a/lib/libc/sys/mq_receive.2 b/lib/libc/sys/mq_receive.2 index 2bbabab..730636b 100644 --- a/lib/libc/sys/mq_receive.2 +++ b/lib/libc/sys/mq_receive.2 @@ -214,4 +214,4 @@ Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at - http://www.opengroup.org/unix/online.html. +http://www.opengroup.org/unix/online.html. diff --git a/lib/libc/sys/mq_send.2 b/lib/libc/sys/mq_send.2 index 6d93a15..6f18b90 100644 --- a/lib/libc/sys/mq_send.2 +++ b/lib/libc/sys/mq_send.2 @@ -233,4 +233,4 @@ Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at - http://www.opengroup.org/unix/online.html. +http://www.opengroup.org/unix/online.html. diff --git a/lib/libc/sys/mq_setattr.2 b/lib/libc/sys/mq_setattr.2 index e1974b4..79e523d 100644 --- a/lib/libc/sys/mq_setattr.2 +++ b/lib/libc/sys/mq_setattr.2 @@ -37,7 +37,7 @@ .\" .\" $FreeBSD$ .\" -.Dd November 29, 2005 +.Dd May 17, 2011 .Dt MQ_SETATTR 2 .Os .Sh NAME @@ -50,7 +50,7 @@ .Ft int .Fo mq_setattr .Fa "mqd_t mqdes" -.Fa "struct mq_attr *restrict mqstat" +.Fa "const struct mq_attr *restrict mqstat" .Fa "struct mq_attr *restrict omqstat" .Fc .Sh DESCRIPTION @@ -120,4 +120,4 @@ Electrical and Electronics Engineers, Inc and The Open Group. In the event of any discrepancy between this version and the original IEEE and The Open Group Standard, the original IEEE and The Open Group Standard is the referee document. The original Standard can be obtained online at - http://www.opengroup.org/unix/online.html. +http://www.opengroup.org/unix/online.html. diff --git a/lib/libc/sys/ntp_adjtime.2 b/lib/libc/sys/ntp_adjtime.2 index 65ff8a3..8ce78e7 100644 --- a/lib/libc/sys/ntp_adjtime.2 +++ b/lib/libc/sys/ntp_adjtime.2 @@ -284,7 +284,7 @@ At the end of the day, second 23:59:59 will be skipped. .It TIME_OOP Leap second in progress. .It TIME_WAIT -Leap second has occurred within the last few seconds.. +Leap second has occurred within the last few seconds. .It TIME_ERROR Clock not synchronized. .El diff --git a/lib/libc/sys/open.2 b/lib/libc/sys/open.2 index 3a5979f..041f9dc 100644 --- a/lib/libc/sys/open.2 +++ b/lib/libc/sys/open.2 @@ -28,7 +28,7 @@ .\" @(#)open.2 8.2 (Berkeley) 11/16/93 .\" $FreeBSD$ .\" -.Dd February 28, 2009 +.Dd March 25, 2011 .Dt OPEN 2 .Os .Sh NAME @@ -117,6 +117,8 @@ O_SYNC synchronous writes O_NOFOLLOW do not follow symlinks O_NOCTTY don't assign controlling terminal O_TTY_INIT restore default terminal attributes +O_DIRECTORY error if file is not a directory +O_CLOEXEC set FD_CLOEXEC upon open .Ed .Pp Opening a file with @@ -222,6 +224,19 @@ The initial call to on a TTY will always restore default terminal attributes on .Fx . .Pp +.Dv O_DIRECTORY +may be used to ensure the resulting file descriptor refers to a +directory. +This flag can be used to prevent applications with elevated privileges +from opening files which are even unsafe to open with +.Dv O_RDONLY , +such as device nodes. +.Pp +.Dv O_CLOEXEC +may be used to set +.Dv FD_CLOEXEC +flag for the newly returned file descriptor. +.Pp If successful, .Fn open returns a non-negative integer, termed a file descriptor. @@ -232,12 +247,17 @@ file is set to the beginning of the file. 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 +Unless +.Dv O_CLOEXEC +flag was specified, +the new descriptor is set to remain open across .Xr execve 2 system calls; see -.Xr close 2 +.Xr close 2 , +.Xr fcntl 2 and -.Xr fcntl 2 . +.Dv O_CLOEXEC +description. .Pp The system imposes a limit on the number of file descriptors open simultaneously by one process. @@ -287,9 +307,9 @@ created has its immutable flag set, see the .Xr chflags 2 manual page for more information. .It Bq Er EPERM -.Dv The named file has its immutable flag set and the file is to be modified. +The named file has its immutable flag set and the file is to be modified. .It Bq Er EPERM -.Dv The named file has its append-only flag set, the file is to be modified, and +The named file has its append-only flag set, the file is to be modified, and .Dv O_TRUNC is specified or .Dv O_APPEND @@ -395,7 +415,7 @@ of .Dv O_WRONLY , .Dv O_RDWR and -.Dv O_EXEC. +.Dv O_EXEC . .It Bq Eq EBADF The .Fa path @@ -413,6 +433,9 @@ argument is not an absolute path and is neither .Dv AT_FDCWD nor a file descriptor associated with a directory. +.It Bq Eq ENOTDIR +.Dv O_DIRECTORY +is specified and the file is not a directory. .El .Sh SEE ALSO .Xr chmod 2 , diff --git a/lib/libc/sys/pathconf.2 b/lib/libc/sys/pathconf.2 index 495bc65..3cfcdbc 100644 --- a/lib/libc/sys/pathconf.2 +++ b/lib/libc/sys/pathconf.2 @@ -89,7 +89,6 @@ returns information about the file the link references. The available values are as follows: .Pp .Bl -tag -width 6n -.Pp .It Li _PC_LINK_MAX The maximum file link count. .It Li _PC_MAX_CANON @@ -234,11 +233,11 @@ Too many symbolic links were encountered in translating the pathname. An I/O error occurred while reading from or writing to the file system. .El .Pp -.Bl -tag -width Er The .Fn fpathconf system call will fail if: +.Bl -tag -width Er .It Bq Er EBADF The .Fa fd diff --git a/lib/libc/sys/posix_fallocate.2 b/lib/libc/sys/posix_fallocate.2 new file mode 100644 index 0000000..f7cbd49 --- /dev/null +++ b/lib/libc/sys/posix_fallocate.2 @@ -0,0 +1,146 @@ +.\" 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. +.\" 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. +.\" +.\" @(#)open.2 8.2 (Berkeley) 11/16/93 +.\" $FreeBSD$ +.\" +.Dd April 13, 2011 +.Dt POSIX_FALLOCATE 2 +.Os +.Sh NAME +.Nm posix_fallocate +.Nd pre-allocate storage for a range in a file +.Sh LIBRARY +.Lb libc +.Sh SYNOPSIS +.In fcntl.h +.Ft int +.Fn posix_fallocate "int fd" "off_t offset" "off_t len" +.Sh DESCRIPTION +Required storage for the range +.Fa offset +to +.Fa offset + +.Fa len +in the file referenced by +.Fa fd +is guarateed to be allocated upon successful return. +That is, if +.Fn posix_fallocate +returns successfully, subsequent writes to the specified file data +will not fail due to lack of free space on the file system storage +media. +Any existing file data in the specified range is unmodified. +If +.Fa offset + +.Fa len +is beyond the current file size, then +.Fn posix_fallocate +will adjust the file size to +.Fa offset + +.Fa len . +Otherwise, the file size will not be changed. +.Pp +Space allocated by +.Fn posix_fallocate +will be freed by a successful call to +.Xr creat 2 +or +.Xr open 2 +that truncates the size of the file. +Space allocated via +.Fn posix_fallocate +may be freed by a successful call to +.Xr ftruncate 2 +that reduces the file size to a size smaller than +.Fa offset + +.Fa len . +.Pp +.Sh RETURN VALUES +If successful, +.Fn posix_fallocate +returns zero. +It returns -1 on failure, and sets +.Va errno +to indicate the error. +.Sh ERRORS +Possible failure conditions: +.Bl -tag -width Er +.It Bq Er EBADF +The +.Fa fd +argument is not a valid file descriptor. +.It Bq Er EBADF +The +.Fa fd +argument references a file that was opened without write permission. +.It Bq Er EFBIG +The value of +.Fa offset + +.Fa len +is greater than the maximum file size. +.It Bq Er EINTR +A signal was caught during execution. +.It Bq Er EINVAL +The +.Fa len +argument was zero or the +.Fa offset +argument was less than zero. +.It Bq Er EIO +An I/O error occurred while reading from or writing to a file system. +.It Bq Er ENODEV +The +.Fa fd +argument does not refer to a regular file. +.It Bq Er ENOSPC +There is insufficient free space remaining on the file system storage +media. +.It Bq Er ESPIPE +The +.Fa fd +argument is associated with a pipe or FIFO. +.El +.Sh SEE ALSO +.Xr creat 2 , +.Xr ftruncate 2 , +.Xr open 2 , +.Xr unlink 2 +.Sh STANDARDS +The +.Fn posix_fallocate +system call conforms to +.St -p1003.1-2004 . +.Sh HISTORY +The +.Fn posix_fallocate +function appeared in +.Fx 9.0 . +.Sh AUTHORS +.Fn posix_fallocate +and this manual page were initially written by +.An Matthew Fleming Aq mdf@FreeBSD.org . diff --git a/lib/libc/sys/ptrace.2 b/lib/libc/sys/ptrace.2 index 8265fb6..1b23c9b 100644 --- a/lib/libc/sys/ptrace.2 +++ b/lib/libc/sys/ptrace.2 @@ -2,7 +2,7 @@ .\" $NetBSD: ptrace.2,v 1.2 1995/02/27 12:35:37 cgd Exp $ .\" .\" This file is in the public domain. -.Dd February 11, 2010 +.Dd January 23, 2011 .Dt PTRACE 2 .Os .Sh NAME @@ -289,8 +289,14 @@ argument specifies a pointer to a which is defined as follows: .Bd -literal struct ptrace_lwpinfo { - lwpid_t pl_lwpid; /* LWP described. */ - int pl_event; /* Event received. */ + lwpid_t pl_lwpid; + int pl_event; + int pl_flags; + sigset_t pl_sigmask; + sigset_t pl_siglist; + siginfo_t pl_siginfo; + char pl_tdname[MAXCOMLEN + 1]; + int pl_child_pid; }; .Ed .Pp @@ -298,6 +304,83 @@ The .Fa data argument is to be set to the size of the structure known to the caller. This allows the structure to grow without affecting older programs. +.Pp +The fields in the +.Vt "struct ptrace_lwpinfo" +have the following meaning: +.Bl -tag -width indent -compact +.It pl_lwpid +LWP id of the thread +.It pl_event +Event that caused the stop. +Currently defined events are +.Bl -tag -width indent -compact +.It PL_EVENT_NONE +No reason given +.It PL_EVENT_SIGNAL +Thread stopped due to the pending signal +.El +.It pl_flags +Flags that specify additional details about observed stop. +Currently defined flags are: +.Bl -tag -width indent -compact +.It PL_FLAG_SCE +The thread stopped due to system call entry, right after the kernel is entered. +The debugger may examine syscall arguments that are stored in memory and +registers according to the ABI of the current process, and modify them, +if needed. +.It PL_FLAG_SCX +The thread is stopped immediately before syscall is returning to the usermode. +The debugger may examine system call return values in the ABI-defined registers +and/or memory. +.It PL_FLAG_EXEC +When +.Dv PL_FLAG_SCX +is set, this flag may be additionally specified to inform that the +program being executed by debuggee process has been changed by successful +execution of a system call from the +.Fn execve 2 +family. +.It PL_FLAG_SI +Indicates that +.Va pl_siginfo +member of +.Vt "struct ptrace_lwpinfo" +contains valid information. +.It PL_FLAG_FORKED +Indicates that the process is returning from a call to +.Fn fork 2 +that created a new child process. +The process identifier of the new process is available in the +.Va pl_child_pid +member of +.Vt "struct ptrace_lwpinfo" . +.El +.It pl_sigmask +The current signal mask of the LWP +.It pl_siglist +The current pending set of signals for the LWP. +Note that signals that are delivered to the process would not appear +on an LWP siglist until the thread is selected for delivery. +.It pl_siginfo +The siginfo that accompanies the signal pending. +Only valid for +.Dv PL_EVENT_SIGNAL +stop when +.Dv PL_FLAG_SI +is set in +.Va pl_flags . +.It pl_tdname +The name of the thread. +.It pl_child_pid +The process identifier of the new child process. +Only valid for a +.Dv PL_EVENT_SIGNAL +stop when +.Dv PL_FLAG_FORKED +is set in +.Va pl_flags . +.El .It PT_GETNUMLWPS This request returns the number of kernel threads associated with the traced process. @@ -327,6 +410,21 @@ This request will trace the specified process on each system call exit. .It PT_SYSCALL This request will trace the specified process on each system call entry and exit. +.It PT_FOLLOW_FORK +This request controls tracing for new child processes of a traced process. +If +.Fa data +is non-zero, +then new child processes will enable tracing and stop before executing their +first instruction. +If +.Fa data +is zero, then new child processes will execute without tracing enabled. +By default, tracing is not enabled for new child processes. +Child processes do not inherit this property. +The traced process will set the +.Dv PL_FLAG_FORKED +flag upon exit from a system call that creates a new process. .It PT_VM_TIMESTAMP This request returns the generation number or timestamp of the memory map of the traced process as the return value from @@ -501,3 +599,11 @@ The .Fn ptrace function appeared in .At v7 . +.Sh BUGS +The +.Dv PL_FLAG_FORKED , +.Dv PL_FLAG_SCE , +.Dv PL_FLAG_SCX +and +.Dv PL_FLAG_EXEC +are not implemented for MIPS and ARM architectures. diff --git a/lib/libc/sys/quotactl.2 b/lib/libc/sys/quotactl.2 index 4b4dca5..ff3cb4b 100644 --- a/lib/libc/sys/quotactl.2 +++ b/lib/libc/sys/quotactl.2 @@ -84,7 +84,7 @@ and group identifiers (GRPQUOTA). The .Dq ufs specific commands are: -.Bl -tag -width Q_QUOTAOFFxx +.Bl -tag -width Q_GETQUOTASIZEx .It Dv Q_QUOTAON Enable disk quotas for the file system specified by .Fa path . @@ -110,6 +110,17 @@ and .Fa id arguments are unused. Only the super-user may turn quotas off. +.It Dv Q_GETQUOTASIZE +Get the wordsize used to represent the quotas for the user or group +(as determined by the command type). +Possible values are 32 for the old-style quota file +and 64 for the new-style quota file. +The +.Fa addr +argument is a pointer to an integer into which the size is stored. +The identifier +.Fa id +is not used. .It Dv Q_GETQUOTA Get disk quota limits and current usage for the user or group (as determined by the command type) with identifier @@ -177,9 +188,11 @@ The argument or the command type is invalid. In -.Dv Q_GETQUOTA -and +.Dv Q_GETQUOTASIZE , +.Dv Q_GETQUOTA , .Dv Q_SETQUOTA , +and +.Dv Q_SETUSE , quotas are not currently enabled for this file system. .Pp The @@ -208,7 +221,8 @@ 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 file system. +either the file system on which quotas are to be enabled is mounted read-only +or the quota file resides on a read-only file system. .It Bq Er EIO An .Tn I/O diff --git a/lib/libc/sys/recv.2 b/lib/libc/sys/recv.2 index e45863e..66f311f 100644 --- a/lib/libc/sys/recv.2 +++ b/lib/libc/sys/recv.2 @@ -165,7 +165,6 @@ system call uses a structure to minimize the number of directly supplied arguments. This structure has the following form, as defined in .In sys/socket.h : -.Pp .Bd -literal struct msghdr { void *msg_name; /* optional address */ @@ -242,7 +241,6 @@ should be a structure of type which is defined in .In sys/socket.h as follows: -.Pp .Bd -literal struct cmsgcred { pid_t cmcred_pid; /* PID of sending process */ diff --git a/lib/libc/sys/rfork.2 b/lib/libc/sys/rfork.2 index c0f264a..f1ae14b 100644 --- a/lib/libc/sys/rfork.2 +++ b/lib/libc/sys/rfork.2 @@ -5,7 +5,7 @@ .\" .\" $FreeBSD$ .\" -.Dd May 14, 2007 +.Dd March 15, 2011 .Dt RFORK 2 .Os .Sh NAME @@ -80,6 +80,7 @@ the new process to run on the provided stack. See .Xr rfork_thread 3 for information. +Note that a lot of code will not run correctly in such an environment. .It Dv RFSIGSHARE If set, the kernel will force sharing the sigacts structure between the child and the parent. @@ -171,24 +172,9 @@ There is insufficient swap space for the new process. .Xr intro 2 , .Xr minherit 2 , .Xr vfork 2 , +.Xr pthread_create 3 , .Xr rfork_thread 3 .Sh HISTORY The .Fn rfork function first appeared in Plan9. -.Sh BUGS -.Fx -does not yet implement a native -.Fn clone -library call, and the current pthreads implementation does not use -.Fn rfork -with RFMEM. -A native port of the linux threads library, -.Pa /usr/ports/devel/linuxthreads , -contains a working -.Fn clone -call that utilizes RFMEM. -The -.Xr rfork_thread 3 -function can often be used instead of -.Fn clone . diff --git a/lib/libc/sys/sched_setscheduler.2 b/lib/libc/sys/sched_setscheduler.2 index 21b34e0..3e7c42b 100644 --- a/lib/libc/sys/sched_setscheduler.2 +++ b/lib/libc/sys/sched_setscheduler.2 @@ -95,7 +95,6 @@ The .Vt sched_param structure is defined in .Fa <sched.h> : -.Pp .Bd -literal -offset indent struct sched_param { int sched_priority; /* scheduling priority */ diff --git a/lib/libc/sys/sctp_peeloff.2 b/lib/libc/sys/sctp_peeloff.2 index c513afa..d94f280 100644 --- a/lib/libc/sys/sctp_peeloff.2 +++ b/lib/libc/sys/sctp_peeloff.2 @@ -50,7 +50,7 @@ The .Fn sctp_peeloff system call attempts detach the association specified by .Fa id -into its own seperate socket. +into its own separate socket. .Pp .Sh RETURN VALUES The call returns -1 on failure and the new socket descriptor diff --git a/lib/libc/sys/semop.2 b/lib/libc/sys/semop.2 index 86200ee..a08f65e 100644 --- a/lib/libc/sys/semop.2 +++ b/lib/libc/sys/semop.2 @@ -222,7 +222,7 @@ When a process exits, either voluntarily or involuntarily, the adjust on exit value for each semaphore is added to the semaphore's value. This can -be used to insure that a resource is released if a process terminates +be used to ensure that a resource is released if a process terminates unexpectedly. .Sh RETURN VALUES .Rv -std semop diff --git a/lib/libc/sys/setuid.2 b/lib/libc/sys/setuid.2 index 78e4ab8..4bb4a68 100644 --- a/lib/libc/sys/setuid.2 +++ b/lib/libc/sys/setuid.2 @@ -124,39 +124,6 @@ The system calls will fail if: The user is not the super user and the ID specified is not the real, effective ID, or saved ID. .El -.Sh SECURITY CONSIDERATIONS -Read and write permissions to files are determined upon a call to -.Xr open 2 . -Once a file descriptor is open, dropping privilege does not affect -the process's read/write permissions, even if the user ID specified -has no read or write permissions to the file. -These files normally remain open in any new process executed, -resulting in a user being able to read or modify -potentially sensitive data. -.Pp -To prevent these files from remaining open after an -.Xr exec 3 -call, be sure to set the close-on-exec flag is set: -.Bd -literal -void -pseudocode(void) -{ - int fd; - /* ... */ - - fd = open("/path/to/sensitive/data", O_RDWR); - if (fd == -1) - err(1, "open"); - - /* - * Set close-on-exec flag; see fcntl(2) for more information. - */ - if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) - err(1, "fcntl(F_SETFD)"); - /* ... */ - execve(path, argv, environ); -} -.Ed .Sh SEE ALSO .Xr getgid 2 , .Xr getuid 2 , @@ -191,3 +158,36 @@ and .Fn setgid functions appeared in .At v7 . +.Sh SECURITY CONSIDERATIONS +Read and write permissions to files are determined upon a call to +.Xr open 2 . +Once a file descriptor is open, dropping privilege does not affect +the process's read/write permissions, even if the user ID specified +has no read or write permissions to the file. +These files normally remain open in any new process executed, +resulting in a user being able to read or modify +potentially sensitive data. +.Pp +To prevent these files from remaining open after an +.Xr exec 3 +call, be sure to set the close-on-exec flag is set: +.Bd -literal +void +pseudocode(void) +{ + int fd; + /* ... */ + + fd = open("/path/to/sensitive/data", O_RDWR); + if (fd == -1) + err(1, "open"); + + /* + * Set close-on-exec flag; see fcntl(2) for more information. + */ + if (fcntl(fd, F_SETFD, FD_CLOEXEC) == -1) + err(1, "fcntl(F_SETFD)"); + /* ... */ + execve(path, argv, environ); +} +.Ed diff --git a/lib/libc/sys/shm_open.2 b/lib/libc/sys/shm_open.2 index a586fe3..a2fa502 100644 --- a/lib/libc/sys/shm_open.2 +++ b/lib/libc/sys/shm_open.2 @@ -231,7 +231,7 @@ is specified and the named shared memory object does not exist. .Dv O_CREAT and .Dv O_EXCL -are specified and the named shared memory object dies exist. +are specified and the named shared memory object does exist. .It Bq Er EACCES The required permissions (for reading or reading and writing) are denied. .El diff --git a/lib/libc/sys/shmat.2 b/lib/libc/sys/shmat.2 index 8fe340c..fd1db93 100644 --- a/lib/libc/sys/shmat.2 +++ b/lib/libc/sys/shmat.2 @@ -35,7 +35,6 @@ .Sh LIBRARY .Lb libc .Sh SYNOPSIS -.In machine/param.h .In sys/types.h .In sys/ipc.h .In sys/shm.h diff --git a/lib/libc/sys/shmctl.2 b/lib/libc/sys/shmctl.2 index d3299af..98ddf13 100644 --- a/lib/libc/sys/shmctl.2 +++ b/lib/libc/sys/shmctl.2 @@ -34,7 +34,6 @@ .Sh LIBRARY .Lb libc .Sh SYNOPSIS -.In machine/param.h .In sys/types.h .In sys/ipc.h .In sys/shm.h diff --git a/lib/libc/sys/shmget.2 b/lib/libc/sys/shmget.2 index e7fd6d1..3094345 100644 --- a/lib/libc/sys/shmget.2 +++ b/lib/libc/sys/shmget.2 @@ -25,7 +25,7 @@ .\" .\" $FreeBSD$ .\" -.Dd July 3, 1995 +.Dd December 17, 2010 .Dt SHMGET 2 .Os .Sh NAME @@ -34,7 +34,6 @@ .Sh LIBRARY .Lb libc .Sh SYNOPSIS -.In machine/param.h .In sys/types.h .In sys/ipc.h .In sys/shm.h @@ -80,17 +79,17 @@ the following constants into the .Fa flag argument: .Bl -tag -width XSHM_WXX6XXX -.It Dv SHM_R -Read access for user. -.It Dv SHM_W -Write access for user. -.It Dv ( SHM_R>>3 ) +.It Dv S_IRUSR +Read access for owner. +.It Dv S_IWUSR +Write access for owner. +.It Dv S_IRGRP Read access for group. -.It Dv ( SHM_W>>3 ) +.It Dv S_IWGRP Write access for group. -.It Dv ( SHM_R>>6 ) +.It Dv S_IROTH Read access for other. -.It Dv ( SHM_W>>6 ) +.It Dv S_IWOTH Write access for other. .El .\" @@ -143,4 +142,5 @@ already exists. .Xr shmat 2 , .Xr shmctl 2 , .Xr shmdt 2 , +.Xr stat 2 , .Xr ftok 3 diff --git a/lib/libc/sys/sigaction.2 b/lib/libc/sys/sigaction.2 index 4c4f18f..47b3a72 100644 --- a/lib/libc/sys/sigaction.2 +++ b/lib/libc/sys/sigaction.2 @@ -28,7 +28,7 @@ .\" From: @(#)sigaction.2 8.2 (Berkeley) 4/3/94 .\" $FreeBSD$ .\" -.Dd June 7, 2004 +.Dd April 18, 2010 .Dt SIGACTION 2 .Os .Sh NAME @@ -40,16 +40,11 @@ .In signal.h .Bd -literal struct sigaction { - union { - void (*__sa_handler)(int); - void (*__sa_sigaction)(int, struct __siginfo *, void *); - } __sigaction_u; /* signal handler */ + void (*sa_handler)(int); + void (*sa_sigaction)(int, siginfo_t *, void *); int sa_flags; /* see signal options below */ sigset_t sa_mask; /* signal mask to apply */ }; - -#define sa_handler __sigaction_u.__sa_handler -#define sa_sigaction __sigaction_u.__sa_sigaction .Ed .Ft int .Fo sigaction @@ -148,6 +143,16 @@ If is non-zero, the previous handling information for the signal is returned to the user. .Pp +The above declaration of +.Vt "struct sigaction" +is not literal. +It is provided only to list the accessible members. +See +.In sys/signal.h +for the actual definition. +In particular, the storage occupied by sa_handler and sa_sigaction overlaps, +and an application can not use both simultaneously. +.Pp Once a signal handler is installed, it normally remains installed until another .Fn sigaction @@ -604,13 +609,9 @@ or .Xr kill 2 , .Xr ptrace 2 , .Xr sigaltstack 2 , -.Xr sigblock 2 , -.Xr sigpause 2 , .Xr sigpending 2 , .Xr sigprocmask 2 , -.Xr sigsetmask 2 , .Xr sigsuspend 2 , -.Xr sigvec 2 , .Xr wait 2 , .Xr fpsetmask 3 , .Xr setjmp 3 , diff --git a/lib/libc/sys/sigaltstack.2 b/lib/libc/sys/sigaltstack.2 index da6877e..d9cb273 100644 --- a/lib/libc/sys/sigaltstack.2 +++ b/lib/libc/sys/sigaltstack.2 @@ -28,7 +28,7 @@ .\" @(#)sigaltstack.2 8.2 (Berkeley) 5/1/95 .\" $FreeBSD$ .\" -.Dd May 1, 1995 +.Dd May 6, 2010 .Dt SIGALTSTACK 2 .Os .Sh NAME @@ -39,7 +39,7 @@ .Sh SYNOPSIS .In signal.h .Bd -literal -typedef struct sigaltstack { +typedef struct { char *ss_sp; size_t ss_size; int ss_flags; @@ -51,25 +51,25 @@ typedef struct sigaltstack { The .Fn sigaltstack system call -allows users to define an alternate stack on which signals -are to be processed. +allows defining an alternate stack on which signals +are to be processed for the current thread. 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. +on which to deliver signals. When a signal's action indicates its handler should execute on the signal stack (specified with a .Xr sigaction 2 system 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, +if the thread is currently executing on that stack. +If the thread 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 +An active stack cannot be modified. +.Pp If .Dv SS_DISABLE is set in @@ -78,12 +78,6 @@ is set in and .Fa ss_size are ignored and the signal stack will be disabled. -Trying to disable an active stack will cause -.Fn sigaltstack -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 @@ -96,7 +90,7 @@ The .Fa ss_flags field will contain the value .Dv SS_ONSTACK -if the process is currently on a signal stack and +if the thread is currently on a signal stack and .Dv SS_DISABLE if the signal stack is currently disabled. .Sh NOTES @@ -110,7 +104,7 @@ if ((sigstk.ss_sp = malloc(SIGSTKSZ)) == NULL) /* error return */ sigstk.ss_size = SIGSTKSZ; sigstk.ss_flags = 0; -if (sigaltstack(&sigstk,0) < 0) +if (sigaltstack(&sigstk, NULL) < 0) perror("sigaltstack"); .Ed An alternative approach is provided for programs with signal handlers @@ -146,8 +140,12 @@ or .Fa oss points to memory that is not a valid part of the process address space. +.It Bq Er EPERM +An attempt was made to modify an active stack. .It Bq Er EINVAL -An attempt was made to disable an active stack. +The +.Fa ss_flags +field was invalid. .It Bq Er ENOMEM Size of alternate stack area is less than or equal to .Dv MINSIGSTKSZ . diff --git a/lib/libc/sys/sigprocmask.2 b/lib/libc/sys/sigprocmask.2 index ef555a4..f7c8335 100644 --- a/lib/libc/sys/sigprocmask.2 +++ b/lib/libc/sys/sigprocmask.2 @@ -28,7 +28,7 @@ .\" @(#)sigprocmask.2 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd June 4, 1993 +.Dd May 7, 2010 .Dt SIGPROCMASK 2 .Os .Sh NAME @@ -96,6 +96,11 @@ quietly disallows or .Dv SIGSTOP to be blocked. +.Pp +In threaded applications, +.Xr pthread_sigmask 3 +must be used instead of +.Fn sigprocmask . .Sh RETURN VALUES .Rv -std sigprocmask .Sh ERRORS @@ -116,6 +121,7 @@ has a value other than those listed here. .Xr sigpending 2 , .Xr sigsuspend 2 , .Xr fpsetmask 3 , +.Xr pthread_sigmask 3 , .Xr sigsetops 3 .Sh STANDARDS The diff --git a/lib/libc/sys/sigreturn.2 b/lib/libc/sys/sigreturn.2 index a022470..02d75a8 100644 --- a/lib/libc/sys/sigreturn.2 +++ b/lib/libc/sys/sigreturn.2 @@ -83,7 +83,7 @@ The process status longword is invalid or would improperly raise the privilege level of the process. .El .Sh SEE ALSO -.Xr sigvec 2 , +.Xr sigaction 2 , .Xr setjmp 3 , .Xr ucontext 3 .Sh HISTORY diff --git a/lib/libc/amd64/gen/ldexp.c b/lib/libc/sys/sigwait.c index 43107fc..2fdffdd 100644 --- a/lib/libc/amd64/gen/ldexp.c +++ b/lib/libc/sys/sigwait.c @@ -1,9 +1,5 @@ /*- - * Copyright (c) 1990, 1993 - * The Regents of the University of California. All rights reserved. - * - * This code is derived from software contributed to Berkeley by - * Sean Eric Fagan. + * Copyright (c) 2010 davidxu@freebsd.org * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions @@ -13,14 +9,11 @@ * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. - * 4. Neither the name of the University nor the names of its contributors - * may be used to endorse or promote products derived from this software - * without specific prior written permission. * - * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND + * THIS SOFTWARE IS PROVIDED BY THE AUTHOR AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE - * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE + * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) @@ -30,33 +23,24 @@ * SUCH DAMAGE. */ -#if defined(LIBC_SCCS) && !defined(lint) -static char sccsid[] = "@(#)ldexp.c 8.1 (Berkeley) 6/4/93"; -#endif /* LIBC_SCCS and not lint */ #include <sys/cdefs.h> __FBSDID("$FreeBSD$"); -/* - * ldexp(value, exp): return value * (2 ** exp). - * - * Written by Sean Eric Fagan (sef@kithrup.COM) - * Sun Mar 11 20:27:09 PST 1990 - */ +#include <errno.h> +#include <signal.h> -/* - * We do the conversion in C to let gcc optimize it away, if possible. - */ -double -ldexp (double value, int exp) +int __sys_sigwait(const sigset_t * restrict, int * restrict); + +__weak_reference(__sigwait, sigwait); + +int +__sigwait(const sigset_t * restrict set, int * restrict sig) { - double temp, texp, temp2; - texp = exp; -#ifdef __GNUC__ - __asm ("fscale " - : "=u" (temp2), "=t" (temp) - : "0" (texp), "1" (value)); -#else -#error unknown asm -#endif - return (temp); + int ret; + + /* POSIX does not allow EINTR to be returned */ + do { + ret = __sys_sigwait(set, sig); + } while (ret == EINTR); + return (ret); } diff --git a/lib/libc/sys/stack_protector.c b/lib/libc/sys/stack_protector.c index 14c20eb..ed7d635 100644 --- a/lib/libc/sys/stack_protector.c +++ b/lib/libc/sys/stack_protector.c @@ -1,4 +1,3 @@ -/* $FreeBSD$ */ /* $NetBSD: stack_protector.c,v 1.4 2006/11/22 17:23:25 christos Exp $ */ /* $OpenBSD: stack_protector.c,v 1.10 2006/03/31 05:34:44 deraadt Exp $ */ /* @@ -34,10 +33,13 @@ __FBSDID("$FreeBSD$"); #include <sys/param.h> #include <sys/sysctl.h> #include <sys/types.h> +#include <errno.h> +#include <link.h> #include <signal.h> #include <string.h> #include <syslog.h> #include <unistd.h> +#include "libc_private.h" extern int __sysctl(int *name, u_int namelen, void *oldp, size_t *oldlenp, void *newp, size_t newlen); @@ -54,9 +56,14 @@ __guard_setup(void) { int mib[2]; size_t len; + int error; if (__stack_chk_guard[0] != 0) return; + error = _elf_aux_info(AT_CANARY, __stack_chk_guard, + sizeof(__stack_chk_guard)); + if (error == 0 && __stack_chk_guard[0] != 0) + return; mib[0] = CTL_KERN; mib[1] = KERN_ARND; @@ -85,7 +92,7 @@ __fail(const char *msg) (void)sigprocmask(SIG_BLOCK, &mask, NULL); /* This may fail on a chroot jail... */ - syslog(LOG_CRIT, msg); + syslog(LOG_CRIT, "%s", msg); (void)memset(&sa, 0, sizeof(sa)); (void)sigemptyset(&sa.sa_mask); @@ -108,8 +115,6 @@ __chk_fail(void) __fail("buffer overflow detected; terminated"); } -#ifdef PIC -__sym_compat(__stack_chk_fail_local, __stack_chk_fail, FBSD_1.0); -#else +#ifndef PIC __weak_reference(__stack_chk_fail, __stack_chk_fail_local); #endif diff --git a/lib/libc/sys/stack_protector_compat.c b/lib/libc/sys/stack_protector_compat.c new file mode 100644 index 0000000..cacb863 --- /dev/null +++ b/lib/libc/sys/stack_protector_compat.c @@ -0,0 +1,20 @@ +/* + * Written by Alexander Kabaev <kan@FreeBSD.org> + * The file is in public domain. + */ + +#include <sys/cdefs.h> +__FBSDID("$FreeBSD$"); + +void __stack_chk_fail(void); + +#ifdef PIC +void +__stack_chk_fail_local_hidden(void) +{ + + __stack_chk_fail(); +} + +__sym_compat(__stack_chk_fail_local, __stack_chk_fail_local_hidden, FBSD_1.0); +#endif diff --git a/lib/libc/sys/stat.2 b/lib/libc/sys/stat.2 index 3085ef0..7f6d533 100644 --- a/lib/libc/sys/stat.2 +++ b/lib/libc/sys/stat.2 @@ -28,7 +28,7 @@ .\" @(#)stat.2 8.4 (Berkeley) 5/1/95 .\" $FreeBSD$ .\" -.Dd April 10, 2008 +.Dd March 28, 2010 .Dt STAT 2 .Os .Sh NAME @@ -149,8 +149,8 @@ fields together identify the file uniquely within the system. The time-related fields of .Vt "struct stat" are as follows: -.Bl -tag -width ".Va st_birthtime" -.It Va st_atime +.Bl -tag -width ".Va st_birthtim" +.It Va st_atim Time when file data last accessed. Changed by the .Xr mknod 2 , @@ -159,7 +159,7 @@ Changed by the and .Xr readv 2 system calls. -.It Va st_mtime +.It Va st_mtim Time when file data last modified. Changed by the .Xr mkdir 2 , @@ -170,7 +170,7 @@ Changed by the and .Xr writev 2 system calls. -.It Va st_ctime +.It Va st_ctim Time when file status was last changed (inode data modification). Changed by the .Xr chflags 2 , @@ -191,18 +191,24 @@ Changed by the and .Xr writev 2 system calls. -.It Va st_birthtime +.It Va st_birthtim Time when the inode was created. .El .Pp -If -.Dv _POSIX_SOURCE -is not defined, the time-related fields are defined as: +The following time-related macros are defined for compatibility: .Bd -literal +#define st_atime st_atim.tv_sec +#define st_mtime st_mtim.tv_sec +#define st_ctime st_ctim.tv_sec +#ifndef _POSIX_SOURCE +#define st_birthtime st_birthtim.tv_sec +#endif + #ifndef _POSIX_SOURCE -#define st_atime st_atimespec.tv_sec -#define st_mtime st_mtimespec.tv_sec -#define st_ctime st_ctimespec.tv_sec +#define st_atimespec st_atim +#define st_mtimespec st_mtim +#define st_ctimespec st_ctim +#define st_birthtimespec st_birthtim #endif .Ed .Pp @@ -339,10 +345,10 @@ represented correctly in the structure pointed to by .Fa sb . .El .Pp -.Bl -tag -width Er The .Fn fstat system call will fail if: +.Bl -tag -width Er .It Bq Er EBADF The .Fa fd @@ -395,8 +401,8 @@ nor a file descriptor associated with a directory. .Xr fhstat 2 , .Xr statfs 2 , .Xr utimes 2 , -.Xr symlink 7 , -.Xr sticky 8 +.Xr sticky 7 , +.Xr symlink 7 .Sh STANDARDS The .Fn stat diff --git a/lib/libc/sys/unlink.2 b/lib/libc/sys/unlink.2 index 141f3d3..bb27085 100644 --- a/lib/libc/sys/unlink.2 +++ b/lib/libc/sys/unlink.2 @@ -28,7 +28,7 @@ .\" @(#)unlink.2 8.1 (Berkeley) 6/4/93 .\" $FreeBSD$ .\" -.Dd April 10, 2008 +.Dd April 25, 2010 .Dt UNLINK 2 .Os .Sh NAME @@ -167,7 +167,7 @@ argument does not specify an absolute path and the argument is neither .Dv AT_FDCWD nor a valid file descriptor open for searching. -.It Bq Er EEXIST +.It Bq Er ENOTEMPTY The .Fa flag parameter has the diff --git a/lib/libc/sys/vfork.2 b/lib/libc/sys/vfork.2 index 3cd3368..1cfaa61 100644 --- a/lib/libc/sys/vfork.2 +++ b/lib/libc/sys/vfork.2 @@ -104,7 +104,7 @@ Same as for .Xr _exit 2 , .Xr fork 2 , .Xr rfork 2 , -.Xr sigvec 2 , +.Xr sigaction 2 , .Xr wait 2 , .Xr exit 3 .Sh HISTORY diff --git a/lib/libc/uuid/uuid.3 b/lib/libc/uuid/uuid.3 index 471629f..4d10204 100644 --- a/lib/libc/uuid/uuid.3 +++ b/lib/libc/uuid/uuid.3 @@ -108,7 +108,6 @@ 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. |