Index: head/lib/libc/rpc/clnt_dg.c =================================================================== --- head/lib/libc/rpc/clnt_dg.c (revision 278931) +++ head/lib/libc/rpc/clnt_dg.c (revision 278932) @@ -1,858 +1,857 @@ /* $NetBSD: clnt_dg.c,v 1.4 2000/07/14 08:40:41 fvdl Exp $ */ /*- * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (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) 1986-1991 by Sun Microsystems Inc. */ #if defined(LIBC_SCCS) && !defined(lint) #ident "@(#)clnt_dg.c 1.23 94/04/22 SMI" static char sccsid[] = "@(#)clnt_dg.c 1.19 89/03/16 Copyr 1988 Sun Micro"; #endif #include __FBSDID("$FreeBSD$"); /* * Implements a connectionless client side RPC. */ #include "namespace.h" #include "reentrant.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "un-namespace.h" #include "rpc_com.h" #include "mt_misc.h" #ifdef _FREEFALL_CONFIG /* * Disable RPC exponential back-off for FreeBSD.org systems. */ #define RPC_MAX_BACKOFF 1 /* second */ #else #define RPC_MAX_BACKOFF 30 /* seconds */ #endif static struct clnt_ops *clnt_dg_ops(void); static bool_t time_not_ok(struct timeval *); static enum clnt_stat clnt_dg_call(CLIENT *, rpcproc_t, xdrproc_t, void *, xdrproc_t, void *, struct timeval); static void clnt_dg_geterr(CLIENT *, struct rpc_err *); static bool_t clnt_dg_freeres(CLIENT *, xdrproc_t, void *); static void clnt_dg_abort(CLIENT *); static bool_t clnt_dg_control(CLIENT *, u_int, void *); static void clnt_dg_destroy(CLIENT *); /* * This machinery implements per-fd locks for MT-safety. It is not * sufficient to do per-CLIENT handle locks for MT-safety because a * user may create more than one CLIENT handle with the same fd behind * it. Therfore, we allocate an array of flags (dg_fd_locks), protected * by the clnt_fd_lock mutex, and an array (dg_cv) of condition variables * similarly protected. Dg_fd_lock[fd] == 1 => a call is activte on some * CLIENT handle created for that fd. * The current implementation holds locks across the entire RPC and reply, * including retransmissions. Yes, this is silly, and as soon as this * code is proven to work, this should be the first thing fixed. One step * at a time. */ static int *dg_fd_locks; static cond_t *dg_cv; #define release_fd_lock(fd, mask) { \ mutex_lock(&clnt_fd_lock); \ dg_fd_locks[fd] = 0; \ mutex_unlock(&clnt_fd_lock); \ thr_sigsetmask(SIG_SETMASK, &(mask), NULL); \ cond_signal(&dg_cv[fd]); \ } static const char mem_err_clnt_dg[] = "clnt_dg_create: out of memory"; /* VARIABLES PROTECTED BY clnt_fd_lock: dg_fd_locks, dg_cv */ #define MCALL_MSG_SIZE 24 /* * Private data kept per client handle */ struct cu_data { int cu_fd; /* connections fd */ bool_t cu_closeit; /* opened by library */ struct sockaddr_storage cu_raddr; /* remote address */ int cu_rlen; struct timeval cu_wait; /* retransmit interval */ struct timeval cu_total; /* total time for the call */ struct rpc_err cu_error; XDR cu_outxdrs; u_int cu_xdrpos; u_int cu_sendsz; /* send size */ char cu_outhdr[MCALL_MSG_SIZE]; char *cu_outbuf; u_int cu_recvsz; /* recv size */ int cu_async; int cu_connect; /* Use connect(). */ int cu_connected; /* Have done connect(). */ struct kevent cu_kin; int cu_kq; char cu_inbuf[1]; }; /* * Connection less client creation returns with client handle parameters. * Default options are set, which the user can change using clnt_control(). * fd should be open and bound. * NB: The rpch->cl_auth is initialized to null authentication. * Caller may wish to set this something more useful. * * sendsz and recvsz are the maximum allowable packet sizes that can be * sent and received. Normally they are the same, but they can be * changed to improve the program efficiency and buffer allocation. * If they are 0, use the transport default. * * If svcaddr is NULL, returns NULL. */ CLIENT * clnt_dg_create(fd, svcaddr, program, version, sendsz, recvsz) int fd; /* open file descriptor */ const struct netbuf *svcaddr; /* servers address */ rpcprog_t program; /* program number */ rpcvers_t version; /* version number */ u_int sendsz; /* buffer recv size */ u_int recvsz; /* buffer send size */ { CLIENT *cl = NULL; /* client handle */ struct cu_data *cu = NULL; /* private data */ struct timeval now; struct rpc_msg call_msg; sigset_t mask; sigset_t newmask; struct __rpc_sockinfo si; int one = 1; sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); mutex_lock(&clnt_fd_lock); if (dg_fd_locks == (int *) NULL) { int cv_allocsz; size_t fd_allocsz; int dtbsize = __rpc_dtbsize(); fd_allocsz = dtbsize * sizeof (int); dg_fd_locks = (int *) mem_alloc(fd_allocsz); if (dg_fd_locks == (int *) NULL) { mutex_unlock(&clnt_fd_lock); thr_sigsetmask(SIG_SETMASK, &(mask), NULL); goto err1; } else memset(dg_fd_locks, '\0', fd_allocsz); cv_allocsz = dtbsize * sizeof (cond_t); dg_cv = (cond_t *) mem_alloc(cv_allocsz); if (dg_cv == (cond_t *) NULL) { mem_free(dg_fd_locks, fd_allocsz); dg_fd_locks = (int *) NULL; mutex_unlock(&clnt_fd_lock); thr_sigsetmask(SIG_SETMASK, &(mask), NULL); goto err1; } else { int i; for (i = 0; i < dtbsize; i++) cond_init(&dg_cv[i], 0, (void *) 0); } } mutex_unlock(&clnt_fd_lock); thr_sigsetmask(SIG_SETMASK, &(mask), NULL); if (svcaddr == NULL) { rpc_createerr.cf_stat = RPC_UNKNOWNADDR; return (NULL); } if (!__rpc_fd2sockinfo(fd, &si)) { rpc_createerr.cf_stat = RPC_TLIERROR; rpc_createerr.cf_error.re_errno = 0; return (NULL); } /* * Find the receive and the send size */ sendsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)sendsz); recvsz = __rpc_get_t_size(si.si_af, si.si_proto, (int)recvsz); if ((sendsz == 0) || (recvsz == 0)) { rpc_createerr.cf_stat = RPC_TLIERROR; /* XXX */ rpc_createerr.cf_error.re_errno = 0; return (NULL); } if ((cl = mem_alloc(sizeof (CLIENT))) == NULL) goto err1; /* * Should be multiple of 4 for XDR. */ sendsz = ((sendsz + 3) / 4) * 4; recvsz = ((recvsz + 3) / 4) * 4; cu = mem_alloc(sizeof (*cu) + sendsz + recvsz); if (cu == NULL) goto err1; (void) memcpy(&cu->cu_raddr, svcaddr->buf, (size_t)svcaddr->len); cu->cu_rlen = svcaddr->len; cu->cu_outbuf = &cu->cu_inbuf[recvsz]; /* Other values can also be set through clnt_control() */ cu->cu_wait.tv_sec = 15; /* heuristically chosen */ cu->cu_wait.tv_usec = 0; cu->cu_total.tv_sec = -1; cu->cu_total.tv_usec = -1; cu->cu_sendsz = sendsz; cu->cu_recvsz = recvsz; cu->cu_async = FALSE; cu->cu_connect = FALSE; cu->cu_connected = FALSE; (void) gettimeofday(&now, NULL); call_msg.rm_xid = __RPC_GETXID(&now); call_msg.rm_call.cb_prog = program; call_msg.rm_call.cb_vers = version; xdrmem_create(&(cu->cu_outxdrs), cu->cu_outhdr, MCALL_MSG_SIZE, XDR_ENCODE); if (! xdr_callhdr(&cu->cu_outxdrs, &call_msg)) { rpc_createerr.cf_stat = RPC_CANTENCODEARGS; /* XXX */ rpc_createerr.cf_error.re_errno = 0; goto err2; } cu->cu_xdrpos = XDR_GETPOS(&(cu->cu_outxdrs)); XDR_DESTROY(&cu->cu_outxdrs); xdrmem_create(&cu->cu_outxdrs, cu->cu_outbuf, sendsz, XDR_ENCODE); /* XXX fvdl - do we still want this? */ #if 0 (void)bindresvport_sa(fd, (struct sockaddr *)svcaddr->buf); #endif _ioctl(fd, FIONBIO, (char *)(void *)&one); /* * By default, closeit is always FALSE. It is users responsibility * to do a close on it, else the user may use clnt_control * to let clnt_destroy do it for him/her. */ cu->cu_closeit = FALSE; cu->cu_fd = fd; cl->cl_ops = clnt_dg_ops(); cl->cl_private = (caddr_t)(void *)cu; cl->cl_auth = authnone_create(); cl->cl_tp = NULL; cl->cl_netid = NULL; cu->cu_kq = -1; EV_SET(&cu->cu_kin, cu->cu_fd, EVFILT_READ, EV_ADD, 0, 0, 0); return (cl); err1: warnx(mem_err_clnt_dg); rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; err2: if (cl) { mem_free(cl, sizeof (CLIENT)); if (cu) mem_free(cu, sizeof (*cu) + sendsz + recvsz); } return (NULL); } static enum clnt_stat clnt_dg_call(cl, proc, xargs, argsp, xresults, resultsp, utimeout) CLIENT *cl; /* client handle */ rpcproc_t proc; /* procedure number */ xdrproc_t xargs; /* xdr routine for args */ void *argsp; /* pointer to args */ xdrproc_t xresults; /* xdr routine for results */ void *resultsp; /* pointer to results */ struct timeval utimeout; /* seconds to wait before giving up */ { struct cu_data *cu = (struct cu_data *)cl->cl_private; XDR *xdrs; size_t outlen = 0; struct rpc_msg reply_msg; XDR reply_xdrs; bool_t ok; int nrefreshes = 2; /* number of times to refresh cred */ int nretries = 0; /* number of times we retransmitted */ struct timeval timeout; struct timeval retransmit_time; struct timeval next_sendtime, starttime, time_waited, tv; struct timespec ts; struct kevent kv; struct sockaddr *sa; sigset_t mask; sigset_t newmask; - socklen_t inlen, salen; + socklen_t salen; ssize_t recvlen = 0; int kin_len, n, rpc_lock_value; u_int32_t xid; outlen = 0; sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); mutex_lock(&clnt_fd_lock); while (dg_fd_locks[cu->cu_fd]) cond_wait(&dg_cv[cu->cu_fd], &clnt_fd_lock); if (__isthreaded) rpc_lock_value = 1; else rpc_lock_value = 0; dg_fd_locks[cu->cu_fd] = rpc_lock_value; mutex_unlock(&clnt_fd_lock); if (cu->cu_total.tv_usec == -1) { timeout = utimeout; /* use supplied timeout */ } else { timeout = cu->cu_total; /* use default timeout */ } if (cu->cu_connect && !cu->cu_connected) { if (_connect(cu->cu_fd, (struct sockaddr *)&cu->cu_raddr, cu->cu_rlen) < 0) { cu->cu_error.re_errno = errno; cu->cu_error.re_status = RPC_CANTSEND; goto out; } cu->cu_connected = 1; } if (cu->cu_connected) { sa = NULL; salen = 0; } else { sa = (struct sockaddr *)&cu->cu_raddr; salen = cu->cu_rlen; } time_waited.tv_sec = 0; time_waited.tv_usec = 0; retransmit_time = next_sendtime = cu->cu_wait; gettimeofday(&starttime, NULL); /* Clean up in case the last call ended in a longjmp(3) call. */ if (cu->cu_kq >= 0) _close(cu->cu_kq); if ((cu->cu_kq = kqueue()) < 0) { cu->cu_error.re_errno = errno; cu->cu_error.re_status = RPC_CANTSEND; goto out; } kin_len = 1; call_again: if (cu->cu_async == TRUE && xargs == NULL) goto get_reply; /* * the transaction is the first thing in the out buffer * XXX Yes, and it's in network byte order, so we should to * be careful when we increment it, shouldn't we. */ xid = ntohl(*(u_int32_t *)(void *)(cu->cu_outhdr)); xid++; *(u_int32_t *)(void *)(cu->cu_outhdr) = htonl(xid); call_again_same_xid: xdrs = &(cu->cu_outxdrs); xdrs->x_op = XDR_ENCODE; XDR_SETPOS(xdrs, 0); if (cl->cl_auth->ah_cred.oa_flavor != RPCSEC_GSS) { if ((! XDR_PUTBYTES(xdrs, cu->cu_outhdr, cu->cu_xdrpos)) || (! XDR_PUTINT32(xdrs, &proc)) || (! AUTH_MARSHALL(cl->cl_auth, xdrs)) || (! (*xargs)(xdrs, argsp))) { cu->cu_error.re_status = RPC_CANTENCODEARGS; goto out; } } else { *(uint32_t *) &cu->cu_outhdr[cu->cu_xdrpos] = htonl(proc); if (!__rpc_gss_wrap(cl->cl_auth, cu->cu_outhdr, cu->cu_xdrpos + sizeof(uint32_t), xdrs, xargs, argsp)) { cu->cu_error.re_status = RPC_CANTENCODEARGS; goto out; } } outlen = (size_t)XDR_GETPOS(xdrs); send_again: if (_sendto(cu->cu_fd, cu->cu_outbuf, outlen, 0, sa, salen) != outlen) { cu->cu_error.re_errno = errno; cu->cu_error.re_status = RPC_CANTSEND; goto out; } /* * Hack to provide rpc-based message passing */ if (timeout.tv_sec == 0 && timeout.tv_usec == 0) { cu->cu_error.re_status = RPC_TIMEDOUT; goto out; } get_reply: /* * sub-optimal code appears here because we have * some clock time to spare while the packets are in flight. * (We assume that this is actually only executed once.) */ reply_msg.acpted_rply.ar_verf = _null_auth; if (cl->cl_auth->ah_cred.oa_flavor != RPCSEC_GSS) { reply_msg.acpted_rply.ar_results.where = resultsp; reply_msg.acpted_rply.ar_results.proc = xresults; } else { reply_msg.acpted_rply.ar_results.where = NULL; reply_msg.acpted_rply.ar_results.proc = (xdrproc_t)xdr_void; } for (;;) { /* Decide how long to wait. */ if (timercmp(&next_sendtime, &timeout, <)) timersub(&next_sendtime, &time_waited, &tv); else timersub(&timeout, &time_waited, &tv); if (tv.tv_sec < 0 || tv.tv_usec < 0) tv.tv_sec = tv.tv_usec = 0; TIMEVAL_TO_TIMESPEC(&tv, &ts); n = _kevent(cu->cu_kq, &cu->cu_kin, kin_len, &kv, 1, &ts); /* We don't need to register the event again. */ kin_len = 0; if (n == 1) { if (kv.flags & EV_ERROR) { cu->cu_error.re_errno = kv.data; cu->cu_error.re_status = RPC_CANTRECV; goto out; } /* We have some data now */ do { recvlen = _recvfrom(cu->cu_fd, cu->cu_inbuf, cu->cu_recvsz, 0, NULL, NULL); } while (recvlen < 0 && errno == EINTR); if (recvlen < 0 && errno != EWOULDBLOCK) { cu->cu_error.re_errno = errno; cu->cu_error.re_status = RPC_CANTRECV; goto out; } if (recvlen >= sizeof(u_int32_t) && (cu->cu_async == TRUE || *((u_int32_t *)(void *)(cu->cu_inbuf)) == *((u_int32_t *)(void *)(cu->cu_outbuf)))) { /* We now assume we have the proper reply. */ break; } } if (n == -1 && errno != EINTR) { cu->cu_error.re_errno = errno; cu->cu_error.re_status = RPC_CANTRECV; goto out; } gettimeofday(&tv, NULL); timersub(&tv, &starttime, &time_waited); /* Check for timeout. */ if (timercmp(&time_waited, &timeout, >)) { cu->cu_error.re_status = RPC_TIMEDOUT; goto out; } /* Retransmit if necessary. */ if (timercmp(&time_waited, &next_sendtime, >)) { /* update retransmit_time */ if (retransmit_time.tv_sec < RPC_MAX_BACKOFF) timeradd(&retransmit_time, &retransmit_time, &retransmit_time); timeradd(&next_sendtime, &retransmit_time, &next_sendtime); nretries++; /* * When retransmitting a RPCSEC_GSS message, * we must use a new sequence number (handled * by __rpc_gss_wrap above). */ if (cl->cl_auth->ah_cred.oa_flavor != RPCSEC_GSS) goto send_again; else goto call_again_same_xid; } } - inlen = (socklen_t)recvlen; /* * now decode and validate the response */ xdrmem_create(&reply_xdrs, cu->cu_inbuf, (u_int)recvlen, XDR_DECODE); ok = xdr_replymsg(&reply_xdrs, &reply_msg); /* XDR_DESTROY(&reply_xdrs); save a few cycles on noop destroy */ if (ok) { if ((reply_msg.rm_reply.rp_stat == MSG_ACCEPTED) && (reply_msg.acpted_rply.ar_stat == SUCCESS)) cu->cu_error.re_status = RPC_SUCCESS; else _seterr_reply(&reply_msg, &(cu->cu_error)); if (cu->cu_error.re_status == RPC_SUCCESS) { if (! AUTH_VALIDATE(cl->cl_auth, &reply_msg.acpted_rply.ar_verf)) { if (nretries && cl->cl_auth->ah_cred.oa_flavor == RPCSEC_GSS) /* * If we retransmitted, its * possible that we will * receive a reply for one of * the earlier transmissions * (which will use an older * RPCSEC_GSS sequence * number). In this case, just * go back and listen for a * new reply. We could keep a * record of all the seq * numbers we have transmitted * so far so that we could * accept a reply for any of * them here. */ goto get_reply; cu->cu_error.re_status = RPC_AUTHERROR; cu->cu_error.re_why = AUTH_INVALIDRESP; } else { if (cl->cl_auth->ah_cred.oa_flavor == RPCSEC_GSS) { if (!__rpc_gss_unwrap(cl->cl_auth, &reply_xdrs, xresults, resultsp)) cu->cu_error.re_status = RPC_CANTDECODERES; } } if (reply_msg.acpted_rply.ar_verf.oa_base != NULL) { xdrs->x_op = XDR_FREE; (void) xdr_opaque_auth(xdrs, &(reply_msg.acpted_rply.ar_verf)); } } /* end successful completion */ /* * If unsuccesful AND error is an authentication error * then refresh credentials and try again, else break */ else if (cu->cu_error.re_status == RPC_AUTHERROR) /* maybe our credentials need to be refreshed ... */ if (nrefreshes > 0 && AUTH_REFRESH(cl->cl_auth, &reply_msg)) { nrefreshes--; goto call_again; } /* end of unsuccessful completion */ } /* end of valid reply message */ else { cu->cu_error.re_status = RPC_CANTDECODERES; } out: if (cu->cu_kq >= 0) _close(cu->cu_kq); cu->cu_kq = -1; release_fd_lock(cu->cu_fd, mask); return (cu->cu_error.re_status); } static void clnt_dg_geterr(cl, errp) CLIENT *cl; struct rpc_err *errp; { struct cu_data *cu = (struct cu_data *)cl->cl_private; *errp = cu->cu_error; } static bool_t clnt_dg_freeres(cl, xdr_res, res_ptr) CLIENT *cl; xdrproc_t xdr_res; void *res_ptr; { struct cu_data *cu = (struct cu_data *)cl->cl_private; XDR *xdrs = &(cu->cu_outxdrs); bool_t dummy; sigset_t mask; sigset_t newmask; sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); mutex_lock(&clnt_fd_lock); while (dg_fd_locks[cu->cu_fd]) cond_wait(&dg_cv[cu->cu_fd], &clnt_fd_lock); xdrs->x_op = XDR_FREE; dummy = (*xdr_res)(xdrs, res_ptr); mutex_unlock(&clnt_fd_lock); thr_sigsetmask(SIG_SETMASK, &mask, NULL); cond_signal(&dg_cv[cu->cu_fd]); return (dummy); } /*ARGSUSED*/ static void clnt_dg_abort(h) CLIENT *h; { } static bool_t clnt_dg_control(cl, request, info) CLIENT *cl; u_int request; void *info; { struct cu_data *cu = (struct cu_data *)cl->cl_private; struct netbuf *addr; sigset_t mask; sigset_t newmask; int rpc_lock_value; sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); mutex_lock(&clnt_fd_lock); while (dg_fd_locks[cu->cu_fd]) cond_wait(&dg_cv[cu->cu_fd], &clnt_fd_lock); if (__isthreaded) rpc_lock_value = 1; else rpc_lock_value = 0; dg_fd_locks[cu->cu_fd] = rpc_lock_value; mutex_unlock(&clnt_fd_lock); switch (request) { case CLSET_FD_CLOSE: cu->cu_closeit = TRUE; release_fd_lock(cu->cu_fd, mask); return (TRUE); case CLSET_FD_NCLOSE: cu->cu_closeit = FALSE; release_fd_lock(cu->cu_fd, mask); return (TRUE); } /* for other requests which use info */ if (info == NULL) { release_fd_lock(cu->cu_fd, mask); return (FALSE); } switch (request) { case CLSET_TIMEOUT: if (time_not_ok((struct timeval *)info)) { release_fd_lock(cu->cu_fd, mask); return (FALSE); } cu->cu_total = *(struct timeval *)info; break; case CLGET_TIMEOUT: *(struct timeval *)info = cu->cu_total; break; case CLGET_SERVER_ADDR: /* Give him the fd address */ /* Now obsolete. Only for backward compatibility */ (void) memcpy(info, &cu->cu_raddr, (size_t)cu->cu_rlen); break; case CLSET_RETRY_TIMEOUT: if (time_not_ok((struct timeval *)info)) { release_fd_lock(cu->cu_fd, mask); return (FALSE); } cu->cu_wait = *(struct timeval *)info; break; case CLGET_RETRY_TIMEOUT: *(struct timeval *)info = cu->cu_wait; break; case CLGET_FD: *(int *)info = cu->cu_fd; break; case CLGET_SVC_ADDR: addr = (struct netbuf *)info; addr->buf = &cu->cu_raddr; addr->len = cu->cu_rlen; addr->maxlen = sizeof cu->cu_raddr; break; case CLSET_SVC_ADDR: /* set to new address */ addr = (struct netbuf *)info; if (addr->len < sizeof cu->cu_raddr) { release_fd_lock(cu->cu_fd, mask); return (FALSE); } (void) memcpy(&cu->cu_raddr, addr->buf, addr->len); cu->cu_rlen = addr->len; break; case CLGET_XID: /* * use the knowledge that xid is the * first element in the call structure *. * This will get the xid of the PREVIOUS call */ *(u_int32_t *)info = ntohl(*(u_int32_t *)(void *)cu->cu_outhdr); break; case CLSET_XID: /* This will set the xid of the NEXT call */ *(u_int32_t *)(void *)cu->cu_outhdr = htonl(*(u_int32_t *)info - 1); /* decrement by 1 as clnt_dg_call() increments once */ break; case CLGET_VERS: /* * This RELIES on the information that, in the call body, * the version number field is the fifth field from the * begining of the RPC header. MUST be changed if the * call_struct is changed */ *(u_int32_t *)info = ntohl(*(u_int32_t *)(void *)(cu->cu_outhdr + 4 * BYTES_PER_XDR_UNIT)); break; case CLSET_VERS: *(u_int32_t *)(void *)(cu->cu_outhdr + 4 * BYTES_PER_XDR_UNIT) = htonl(*(u_int32_t *)info); break; case CLGET_PROG: /* * This RELIES on the information that, in the call body, * the program number field is the fourth field from the * begining of the RPC header. MUST be changed if the * call_struct is changed */ *(u_int32_t *)info = ntohl(*(u_int32_t *)(void *)(cu->cu_outhdr + 3 * BYTES_PER_XDR_UNIT)); break; case CLSET_PROG: *(u_int32_t *)(void *)(cu->cu_outhdr + 3 * BYTES_PER_XDR_UNIT) = htonl(*(u_int32_t *)info); break; case CLSET_ASYNC: cu->cu_async = *(int *)info; break; case CLSET_CONNECT: cu->cu_connect = *(int *)info; break; default: release_fd_lock(cu->cu_fd, mask); return (FALSE); } release_fd_lock(cu->cu_fd, mask); return (TRUE); } static void clnt_dg_destroy(cl) CLIENT *cl; { struct cu_data *cu = (struct cu_data *)cl->cl_private; int cu_fd = cu->cu_fd; sigset_t mask; sigset_t newmask; sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); mutex_lock(&clnt_fd_lock); while (dg_fd_locks[cu_fd]) cond_wait(&dg_cv[cu_fd], &clnt_fd_lock); if (cu->cu_closeit) (void)_close(cu_fd); if (cu->cu_kq >= 0) _close(cu->cu_kq); XDR_DESTROY(&(cu->cu_outxdrs)); mem_free(cu, (sizeof (*cu) + cu->cu_sendsz + cu->cu_recvsz)); if (cl->cl_netid && cl->cl_netid[0]) mem_free(cl->cl_netid, strlen(cl->cl_netid) +1); if (cl->cl_tp && cl->cl_tp[0]) mem_free(cl->cl_tp, strlen(cl->cl_tp) +1); mem_free(cl, sizeof (CLIENT)); mutex_unlock(&clnt_fd_lock); thr_sigsetmask(SIG_SETMASK, &mask, NULL); cond_signal(&dg_cv[cu_fd]); } static struct clnt_ops * clnt_dg_ops() { static struct clnt_ops ops; sigset_t mask; sigset_t newmask; /* VARIABLES PROTECTED BY ops_lock: ops */ sigfillset(&newmask); thr_sigsetmask(SIG_SETMASK, &newmask, &mask); mutex_lock(&ops_lock); if (ops.cl_call == NULL) { ops.cl_call = clnt_dg_call; ops.cl_abort = clnt_dg_abort; ops.cl_geterr = clnt_dg_geterr; ops.cl_freeres = clnt_dg_freeres; ops.cl_destroy = clnt_dg_destroy; ops.cl_control = clnt_dg_control; } mutex_unlock(&ops_lock); thr_sigsetmask(SIG_SETMASK, &mask, NULL); return (&ops); } /* * Make sure that the time is not garbage. -1 value is allowed. */ static bool_t time_not_ok(t) struct timeval *t; { return (t->tv_sec < -1 || t->tv_sec > 100000000 || t->tv_usec < -1 || t->tv_usec > 1000000); } Index: head/lib/libc/rpc/rpc_soc.c =================================================================== --- head/lib/libc/rpc/rpc_soc.c (revision 278931) +++ head/lib/libc/rpc/rpc_soc.c (revision 278932) @@ -1,581 +1,579 @@ /* $NetBSD: rpc_soc.c,v 1.6 2000/07/06 03:10:35 christos Exp $ */ /*- * Copyright (c) 2009, Sun Microsystems, Inc. * All rights reserved. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * - Redistributions of source code must retain the above copyright notice, * this list of conditions and the following disclaimer. * - Redistributions in binary form must reproduce the above copyright notice, * this list of conditions and the following disclaimer in the documentation * and/or other materials provided with the distribution. * - Neither the name of Sun Microsystems, 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 HOLDER OR CONTRIBUTORS BE * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE * POSSIBILITY OF SUCH DAMAGE. */ /* #ident "@(#)rpc_soc.c 1.17 94/04/24 SMI" */ /* * Copyright (c) 1986-1991 by Sun Microsystems Inc. * In addition, portions of such source code were derived from Berkeley * 4.3 BSD under license from the Regents of the University of * California. */ #if defined(LIBC_SCCS) && !defined(lint) static char sccsid[] = "@(#)rpc_soc.c 1.41 89/05/02 Copyr 1988 Sun Micro"; #endif #include __FBSDID("$FreeBSD$"); #ifdef PORTMAP /* * rpc_soc.c * * The backward compatibility routines for the earlier implementation * of RPC, where the only transports supported were tcp/ip and udp/ip. * Based on berkeley socket abstraction, now implemented on the top * of TLI/Streams */ #include "namespace.h" #include "reentrant.h" #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "un-namespace.h" #include "rpc_com.h" #include "mt_misc.h" static CLIENT *clnt_com_create(struct sockaddr_in *, rpcprog_t, rpcvers_t, int *, u_int, u_int, char *); static SVCXPRT *svc_com_create(int, u_int, u_int, char *); static bool_t rpc_wrap_bcast(char *, struct netbuf *, struct netconfig *); /* XXX */ #define IN4_LOCALHOST_STRING "127.0.0.1" #define IN6_LOCALHOST_STRING "::1" /* * A common clnt create routine */ static CLIENT * clnt_com_create(raddr, prog, vers, sockp, sendsz, recvsz, tp) struct sockaddr_in *raddr; rpcprog_t prog; rpcvers_t vers; int *sockp; u_int sendsz; u_int recvsz; char *tp; { CLIENT *cl; int madefd = FALSE; int fd = *sockp; struct netconfig *nconf; struct netbuf bindaddr; mutex_lock(&rpcsoc_lock); if ((nconf = __rpc_getconfip(tp)) == NULL) { rpc_createerr.cf_stat = RPC_UNKNOWNPROTO; mutex_unlock(&rpcsoc_lock); return (NULL); } if (fd == RPC_ANYSOCK) { fd = __rpc_nconf2fd(nconf); if (fd == -1) goto syserror; madefd = TRUE; } if (raddr->sin_port == 0) { u_int proto; u_short sport; mutex_unlock(&rpcsoc_lock); /* pmap_getport is recursive */ proto = strcmp(tp, "udp") == 0 ? IPPROTO_UDP : IPPROTO_TCP; sport = pmap_getport(raddr, (u_long)prog, (u_long)vers, proto); if (sport == 0) { goto err; } raddr->sin_port = htons(sport); mutex_lock(&rpcsoc_lock); /* pmap_getport is recursive */ } /* Transform sockaddr_in to netbuf */ bindaddr.maxlen = bindaddr.len = sizeof (struct sockaddr_in); bindaddr.buf = raddr; bindresvport(fd, NULL); cl = clnt_tli_create(fd, nconf, &bindaddr, prog, vers, sendsz, recvsz); if (cl) { if (madefd == TRUE) { /* * The fd should be closed while destroying the handle. */ (void) CLNT_CONTROL(cl, CLSET_FD_CLOSE, NULL); *sockp = fd; } (void) freenetconfigent(nconf); mutex_unlock(&rpcsoc_lock); return (cl); } goto err; syserror: rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; err: if (madefd == TRUE) (void)_close(fd); (void) freenetconfigent(nconf); mutex_unlock(&rpcsoc_lock); return (NULL); } CLIENT * clntudp_bufcreate(raddr, prog, vers, wait, sockp, sendsz, recvsz) struct sockaddr_in *raddr; u_long prog; u_long vers; struct timeval wait; int *sockp; u_int sendsz; u_int recvsz; { CLIENT *cl; cl = clnt_com_create(raddr, (rpcprog_t)prog, (rpcvers_t)vers, sockp, sendsz, recvsz, "udp"); if (cl == NULL) { return (NULL); } (void) CLNT_CONTROL(cl, CLSET_RETRY_TIMEOUT, &wait); return (cl); } CLIENT * clntudp_create(raddr, program, version, wait, sockp) struct sockaddr_in *raddr; u_long program; u_long version; struct timeval wait; int *sockp; { return clntudp_bufcreate(raddr, program, version, wait, sockp, UDPMSGSIZE, UDPMSGSIZE); } CLIENT * clnttcp_create(raddr, prog, vers, sockp, sendsz, recvsz) struct sockaddr_in *raddr; u_long prog; u_long vers; int *sockp; u_int sendsz; u_int recvsz; { return clnt_com_create(raddr, (rpcprog_t)prog, (rpcvers_t)vers, sockp, sendsz, recvsz, "tcp"); } CLIENT * clntraw_create(prog, vers) u_long prog; u_long vers; { return clnt_raw_create((rpcprog_t)prog, (rpcvers_t)vers); } /* * A common server create routine */ static SVCXPRT * svc_com_create(fd, sendsize, recvsize, netid) int fd; u_int sendsize; u_int recvsize; char *netid; { struct netconfig *nconf; SVCXPRT *svc; int madefd = FALSE; int port; struct sockaddr_in sin; if ((nconf = __rpc_getconfip(netid)) == NULL) { (void) syslog(LOG_ERR, "Could not get %s transport", netid); return (NULL); } if (fd == RPC_ANYSOCK) { fd = __rpc_nconf2fd(nconf); if (fd == -1) { (void) freenetconfigent(nconf); (void) syslog(LOG_ERR, "svc%s_create: could not open connection", netid); return (NULL); } madefd = TRUE; } memset(&sin, 0, sizeof sin); sin.sin_family = AF_INET; bindresvport(fd, &sin); _listen(fd, SOMAXCONN); svc = svc_tli_create(fd, nconf, NULL, sendsize, recvsize); (void) freenetconfigent(nconf); if (svc == NULL) { if (madefd) (void)_close(fd); return (NULL); } port = (((struct sockaddr_in *)svc->xp_ltaddr.buf)->sin_port); svc->xp_port = ntohs(port); return (svc); } SVCXPRT * svctcp_create(fd, sendsize, recvsize) int fd; u_int sendsize; u_int recvsize; { return svc_com_create(fd, sendsize, recvsize, "tcp"); } SVCXPRT * svcudp_bufcreate(fd, sendsz, recvsz) int fd; u_int sendsz, recvsz; { return svc_com_create(fd, sendsz, recvsz, "udp"); } SVCXPRT * svcfd_create(fd, sendsize, recvsize) int fd; u_int sendsize; u_int recvsize; { return svc_fd_create(fd, sendsize, recvsize); } SVCXPRT * svcudp_create(fd) int fd; { return svc_com_create(fd, UDPMSGSIZE, UDPMSGSIZE, "udp"); } SVCXPRT * svcraw_create() { return svc_raw_create(); } int get_myaddress(addr) struct sockaddr_in *addr; { memset((void *) addr, 0, sizeof(*addr)); addr->sin_family = AF_INET; addr->sin_port = htons(PMAPPORT); addr->sin_addr.s_addr = htonl(INADDR_LOOPBACK); return (0); } /* * For connectionless "udp" transport. Obsoleted by rpc_call(). */ int callrpc(host, prognum, versnum, procnum, inproc, in, outproc, out) const char *host; int prognum, versnum, procnum; xdrproc_t inproc, outproc; void *in, *out; { return (int)rpc_call(host, (rpcprog_t)prognum, (rpcvers_t)versnum, (rpcproc_t)procnum, inproc, in, outproc, out, "udp"); } /* * For connectionless kind of transport. Obsoleted by rpc_reg() */ int registerrpc(prognum, versnum, procnum, progname, inproc, outproc) int prognum, versnum, procnum; char *(*progname)(char [UDPMSGSIZE]); xdrproc_t inproc, outproc; { return rpc_reg((rpcprog_t)prognum, (rpcvers_t)versnum, (rpcproc_t)procnum, progname, inproc, outproc, "udp"); } /* * All the following clnt_broadcast stuff is convulated; it supports * the earlier calling style of the callback function */ 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. * Dont care about netid here. */ /* ARGSUSED */ static bool_t rpc_wrap_bcast(resultp, addr, nconf) char *resultp; /* results of the call */ struct netbuf *addr; /* address of the guy who responded */ struct netconfig *nconf; /* Netconf of the transport */ { resultproc_t clnt_broadcast_result; if (strcmp(nconf->nc_netid, "udp")) return (FALSE); if (thr_main()) clnt_broadcast_result = clnt_broadcast_result_main; else clnt_broadcast_result = (resultproc_t)thr_getspecific(clnt_broadcast_key); return (*clnt_broadcast_result)(resultp, (struct sockaddr_in *)addr->buf); } /* * Broadcasts on UDP transport. Obsoleted by rpc_broadcast(). */ enum clnt_stat clnt_broadcast(prog, vers, proc, xargs, argsp, xresults, resultsp, eachresult) u_long prog; /* program number */ u_long vers; /* version number */ u_long proc; /* procedure number */ xdrproc_t xargs; /* xdr routine for args */ void *argsp; /* pointer to args */ xdrproc_t xresults; /* xdr routine for results */ void *resultsp; /* pointer to results */ resultproc_t eachresult; /* call with each result obtained */ { if (thr_main()) clnt_broadcast_result_main = eachresult; else { 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, (rpcproc_t)proc, xargs, argsp, xresults, resultsp, (resultproc_t) rpc_wrap_bcast, "udp"); } /* * Create the client des authentication object. Obsoleted by * authdes_seccreate(). */ AUTH * authdes_create(servername, window, syncaddr, ckey) char *servername; /* network name of server */ u_int window; /* time to live */ struct sockaddr *syncaddr; /* optional hostaddr to sync with */ des_block *ckey; /* optional conversation key to use */ { AUTH *dummy; AUTH *nauth; char hostname[NI_MAXHOST]; if (syncaddr) { /* * Change addr to hostname, because that is the way * new interface takes it. */ if (getnameinfo(syncaddr, syncaddr->sa_len, hostname, sizeof hostname, NULL, 0, 0) != 0) goto fallback; nauth = authdes_seccreate(servername, window, hostname, ckey); return (nauth); } fallback: dummy = authdes_seccreate(servername, window, NULL, ckey); return (dummy); } /* * Create a client handle for a unix connection. Obsoleted by clnt_vc_create() */ CLIENT * clntunix_create(raddr, prog, vers, sockp, sendsz, recvsz) struct sockaddr_un *raddr; u_long prog; u_long vers; int *sockp; u_int sendsz; u_int recvsz; { struct netbuf *svcaddr; - struct netconfig *nconf; CLIENT *cl; int len; cl = NULL; - nconf = NULL; svcaddr = NULL; if ((raddr->sun_len == 0) || ((svcaddr = malloc(sizeof(struct netbuf))) == NULL ) || ((svcaddr->buf = malloc(sizeof(struct sockaddr_un))) == NULL)) { if (svcaddr != NULL) free(svcaddr); rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; return(cl); } if (*sockp < 0) { *sockp = _socket(AF_LOCAL, SOCK_STREAM, 0); len = raddr->sun_len = SUN_LEN(raddr); if ((*sockp < 0) || (_connect(*sockp, (struct sockaddr *)raddr, len) < 0)) { rpc_createerr.cf_stat = RPC_SYSTEMERROR; rpc_createerr.cf_error.re_errno = errno; if (*sockp != -1) (void)_close(*sockp); goto done; } } svcaddr->buf = raddr; svcaddr->len = raddr->sun_len; svcaddr->maxlen = sizeof (struct sockaddr_un); cl = clnt_vc_create(*sockp, svcaddr, prog, vers, sendsz, recvsz); done: free(svcaddr->buf); free(svcaddr); return(cl); } /* * Creates, registers, and returns a (rpc) unix based transporter. * Obsoleted by svc_vc_create(). */ SVCXPRT * svcunix_create(sock, sendsize, recvsize, path) int sock; u_int sendsize; u_int recvsize; char *path; { struct netconfig *nconf; void *localhandle; struct sockaddr_un sun; struct sockaddr *sa; struct t_bind taddr; SVCXPRT *xprt; int addrlen; xprt = (SVCXPRT *)NULL; localhandle = setnetconfig(); while ((nconf = getnetconfig(localhandle)) != NULL) { if (nconf->nc_protofmly != NULL && strcmp(nconf->nc_protofmly, NC_LOOPBACK) == 0) break; } if (nconf == NULL) return(xprt); if ((sock = __rpc_nconf2fd(nconf)) < 0) goto done; memset(&sun, 0, sizeof sun); sun.sun_family = AF_LOCAL; if (strlcpy(sun.sun_path, path, sizeof(sun.sun_path)) >= sizeof(sun.sun_path)) goto done; sun.sun_len = SUN_LEN(&sun); addrlen = sizeof (struct sockaddr_un); sa = (struct sockaddr *)&sun; if (_bind(sock, sa, addrlen) < 0) goto done; taddr.addr.len = taddr.addr.maxlen = addrlen; taddr.addr.buf = malloc(addrlen); if (taddr.addr.buf == NULL) goto done; memcpy(taddr.addr.buf, sa, addrlen); if (nconf->nc_semantics != NC_TPI_CLTS) { if (_listen(sock, SOMAXCONN) < 0) { free(taddr.addr.buf); goto done; } } xprt = (SVCXPRT *)svc_tli_create(sock, nconf, &taddr, sendsize, recvsize); done: endnetconfig(localhandle); return(xprt); } /* * Like svunix_create(), except the routine takes any *open* UNIX file * descriptor as its first input. Obsoleted by svc_fd_create(); */ SVCXPRT * svcunixfd_create(fd, sendsize, recvsize) int fd; u_int sendsize; u_int recvsize; { return (svc_fd_create(fd, sendsize, recvsize)); } #endif /* PORTMAP */ Index: head/lib/libc/stdio/xprintf_float.c =================================================================== --- head/lib/libc/stdio/xprintf_float.c (revision 278931) +++ head/lib/libc/stdio/xprintf_float.c (revision 278932) @@ -1,425 +1,422 @@ /*- * Copyright (c) 2005 Poul-Henning Kamp * Copyright (c) 1990, 1993 * The Regents of the University of California. All rights reserved. * * This code is derived from software contributed to Berkeley by * Chris Torek. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions * are met: * 1. Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * 2. Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * 3. Neither the name of the University nor the names of its contributors * may be used to endorse or promote products derived from this software * without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE REGENTS AND CONTRIBUTORS ``AS IS'' AND * ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE * ARE DISCLAIMED. IN NO EVENT SHALL THE REGENTS OR CONTRIBUTORS BE LIABLE * FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL * DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS * OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) * HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT * LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY * OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. * * $FreeBSD$ */ #include #include #include #include #include #include #define dtoa __dtoa #define freedtoa __freedtoa #include #include #include "gdtoa.h" #include "floatio.h" #include "printf.h" #include /* * The size of the buffer we use as scratch space for integer * conversions, among other things. Technically, we would need the * most space for base 10 conversions with thousands' grouping * characters between each pair of digits. 100 bytes is a * conservative overestimate even for a 128-bit uintmax_t. */ #define BUF 100 #define DEFPREC 6 /* Default FP precision */ /* various globals ---------------------------------------------------*/ /* padding function---------------------------------------------------*/ #define PRINTANDPAD(p, ep, len, with) do { \ n2 = (ep) - (p); \ if (n2 > (len)) \ n2 = (len); \ if (n2 > 0) \ ret += __printf_puts(io, (p), n2); \ ret += __printf_pad(io, (len) - (n2 > 0 ? n2 : 0), (with)); \ } while(0) /* misc --------------------------------------------------------------*/ #define to_char(n) ((n) + '0') static int exponent(char *p0, int expo, int fmtch) { char *p, *t; char expbuf[MAXEXPDIG]; p = p0; *p++ = fmtch; if (expo < 0) { expo = -expo; *p++ = '-'; } else *p++ = '+'; t = expbuf + MAXEXPDIG; if (expo > 9) { do { *--t = to_char(expo % 10); } while ((expo /= 10) > 9); *--t = to_char(expo); for (; t < expbuf + MAXEXPDIG; *p++ = *t++) ; } else { /* * Exponents for decimal floating point conversions * (%[eEgG]) must be at least two characters long, * whereas exponents for hexadecimal conversions can * be only one character long. */ if (fmtch == 'e' || fmtch == 'E') *p++ = '0'; *p++ = to_char(expo); } return (p - p0); } /* 'f' ---------------------------------------------------------------*/ int __printf_arginfo_float(const struct printf_info *pi, size_t n, int *argt) { assert (n > 0); argt[0] = PA_DOUBLE; if (pi->is_long_double) argt[0] |= PA_FLAG_LONG_DOUBLE; return (1); } /* * We can decompose the printed representation of floating * point numbers into several parts, some of which may be empty: * * [+|-| ] [0x|0X] MMM . NNN [e|E|p|P] [+|-] ZZ * A B ---C--- D E F * * A: 'sign' holds this value if present; '\0' otherwise * B: ox[1] holds the 'x' or 'X'; '\0' if not hexadecimal * C: cp points to the string MMMNNN. Leading and trailing * zeros are not in the string and must be added. * D: expchar holds this character; '\0' if no exponent, e.g. %f * F: at least two digits for decimal, at least one digit for hex */ int __printf_render_float(struct __printf_io *io, const struct printf_info *pi, const void *const *arg) { int prec; /* precision from format; <0 for N/A */ char *dtoaresult; /* buffer allocated by dtoa */ char expchar; /* exponent character: [eEpP\0] */ char *cp; int expt; /* integer value of exponent */ int signflag; /* true if float is negative */ char *dtoaend; /* pointer to end of converted digits */ char sign; /* sign prefix (' ', '+', '-', or \0) */ int size; /* size of converted field or string */ int ndig; /* actual number of digits returned by dtoa */ int expsize; /* character count for expstr */ char expstr[MAXEXPDIG+2]; /* buffer for exponent string: e+ZZZ */ int nseps; /* number of group separators with ' */ int nrepeats; /* number of repeats of the last group */ const char *grouping; /* locale specific numeric grouping rules */ int lead; /* sig figs before decimal or group sep */ long double ld; double d; int realsz; /* field size expanded by dprec, sign, etc */ int dprec; /* a copy of prec if [diouxX], 0 otherwise */ char ox[2]; /* space for 0x; ox[1] is either x, X, or \0 */ - int prsize; /* max size of printed field */ int ret; /* return value accumulator */ char *decimal_point; /* locale specific decimal point */ int n2; /* XXX: for PRINTANDPAD */ char thousands_sep; /* locale specific thousands separator */ char buf[BUF]; /* buffer with space for digits of uintmax_t */ const char *xdigs; int flag; prec = pi->prec; ox[1] = '\0'; sign = pi->showsign; flag = 0; ret = 0; thousands_sep = *(localeconv()->thousands_sep); grouping = NULL; if (pi->alt) grouping = localeconv()->grouping; decimal_point = localeconv()->decimal_point; dprec = -1; switch(pi->spec) { case 'a': case 'A': if (pi->spec == 'a') { ox[1] = 'x'; xdigs = __lowercase_hex; expchar = 'p'; } else { ox[1] = 'X'; xdigs = __uppercase_hex; expchar = 'P'; } if (prec >= 0) prec++; if (pi->is_long_double) { ld = *((long double *)arg[0]); dtoaresult = cp = __hldtoa(ld, xdigs, prec, &expt, &signflag, &dtoaend); } else { d = *((double *)arg[0]); dtoaresult = cp = __hdtoa(d, xdigs, prec, &expt, &signflag, &dtoaend); } if (prec < 0) prec = dtoaend - cp; if (expt == INT_MAX) ox[1] = '\0'; goto fp_common; case 'e': case 'E': expchar = pi->spec; if (prec < 0) /* account for digit before decpt */ prec = DEFPREC + 1; else prec++; break; case 'f': case 'F': expchar = '\0'; break; case 'g': case 'G': expchar = pi->spec - ('g' - 'e'); if (prec == 0) prec = 1; break; default: assert(pi->spec == 'f'); } if (prec < 0) prec = DEFPREC; if (pi->is_long_double) { ld = *((long double *)arg[0]); dtoaresult = cp = __ldtoa(&ld, expchar ? 2 : 3, prec, &expt, &signflag, &dtoaend); } else { d = *((double *)arg[0]); dtoaresult = cp = dtoa(d, expchar ? 2 : 3, prec, &expt, &signflag, &dtoaend); if (expt == 9999) expt = INT_MAX; } fp_common: if (signflag) sign = '-'; if (expt == INT_MAX) { /* inf or nan */ if (*cp == 'N') { cp = (pi->spec >= 'a') ? "nan" : "NAN"; sign = '\0'; } else cp = (pi->spec >= 'a') ? "inf" : "INF"; size = 3; flag = 1; goto here; } ndig = dtoaend - cp; if (pi->spec == 'g' || pi->spec == 'G') { if (expt > -4 && expt <= prec) { /* Make %[gG] smell like %[fF] */ expchar = '\0'; if (pi->alt) prec -= expt; else prec = ndig - expt; if (prec < 0) prec = 0; } else { /* * Make %[gG] smell like %[eE], but * trim trailing zeroes if no # flag. */ if (!pi->alt) prec = ndig; } } if (expchar) { expsize = exponent(expstr, expt - 1, expchar); size = expsize + prec; if (prec > 1 || pi->alt) ++size; } else { /* space for digits before decimal point */ if (expt > 0) size = expt; else /* "0" */ size = 1; /* space for decimal pt and following digits */ if (prec || pi->alt) size += prec + 1; if (grouping && expt > 0) { /* space for thousands' grouping */ nseps = nrepeats = 0; lead = expt; while (*grouping != CHAR_MAX) { if (lead <= *grouping) break; lead -= *grouping; if (*(grouping+1)) { nseps++; grouping++; } else nrepeats++; } size += nseps + nrepeats; } else lead = expt; } here: /* * All reasonable formats wind up here. At this point, `cp' * points to a string which (if not flags&LADJUST) should be * padded out to `width' places. If flags&ZEROPAD, it should * first be prefixed by any sign or other prefix; otherwise, * it should be blank padded before the prefix is emitted. * After any left-hand padding and prefixing, emit zeroes * required by a decimal [diouxX] precision, then print the * string proper, then emit zeroes required by any leftover * floating precision; finally, if LADJUST, pad with blanks. * * Compute actual size, so we know how much to pad. * size excludes decimal prec; realsz includes it. */ realsz = dprec > size ? dprec : size; if (sign) realsz++; if (ox[1]) realsz += 2; - - prsize = pi->width > realsz ? pi->width : realsz; /* right-adjusting blank padding */ if (pi->pad != '0' && pi->left == 0) ret += __printf_pad(io, pi->width - realsz, 0); /* prefix */ if (sign) ret += __printf_puts(io, &sign, 1); if (ox[1]) { /* ox[1] is either x, X, or \0 */ ox[0] = '0'; ret += __printf_puts(io, ox, 2); } /* right-adjusting zero padding */ if (pi->pad == '0' && pi->left == 0) ret += __printf_pad(io, pi->width - realsz, 1); /* leading zeroes from decimal precision */ ret += __printf_pad(io, dprec - size, 1); if (flag) ret += __printf_puts(io, cp, size); else { /* glue together f_p fragments */ if (!expchar) { /* %[fF] or sufficiently short %[gG] */ if (expt <= 0) { ret += __printf_puts(io, "0", 1); if (prec || pi->alt) ret += __printf_puts(io, decimal_point, 1); ret += __printf_pad(io, -expt, 1); /* already handled initial 0's */ prec += expt; } else { PRINTANDPAD(cp, dtoaend, lead, 1); cp += lead; if (grouping) { while (nseps>0 || nrepeats>0) { if (nrepeats > 0) nrepeats--; else { grouping--; nseps--; } ret += __printf_puts(io, &thousands_sep, 1); PRINTANDPAD(cp,dtoaend, *grouping, 1); cp += *grouping; } if (cp > dtoaend) cp = dtoaend; } if (prec || pi->alt) ret += __printf_puts(io, decimal_point,1); } PRINTANDPAD(cp, dtoaend, prec, 1); } else { /* %[eE] or sufficiently long %[gG] */ if (prec > 1 || pi->alt) { buf[0] = *cp++; buf[1] = *decimal_point; ret += __printf_puts(io, buf, 2); ret += __printf_puts(io, cp, ndig-1); ret += __printf_pad(io, prec - ndig, 1); } else /* XeYYY */ ret += __printf_puts(io, cp, 1); ret += __printf_puts(io, expstr, expsize); } } /* left-adjusting padding (always blank) */ if (pi->left) ret += __printf_pad(io, pi->width - realsz, 0); __printf_flush(io); if (dtoaresult != NULL) freedtoa(dtoaresult); return (ret); }