xref: /netbsd-src/external/bsd/libbind/dist/bsd/gettimeofday.c (revision 5bbd2a12505d72a8177929a37b5cee489d0a1cfd)
1 /*	$NetBSD: gettimeofday.c,v 1.1.1.2 2012/09/09 16:07:42 christos Exp $	*/
2 
3 #ifndef LINT
4 static const char rcsid[] = "Id: gettimeofday.c,v 1.4 2005/04/27 04:56:11 sra Exp ";
5 #endif
6 
7 #include "port_before.h"
8 #include <stdio.h>
9 #include <syslog.h>
10 #include <sys/time.h>
11 #include "port_after.h"
12 
13 #if !defined(NEED_GETTIMEOFDAY)
14 /*%
15  * gettimeofday() occasionally returns invalid tv_usec on some platforms.
16  */
17 #define MILLION 1000000
18 #undef gettimeofday
19 
20 int
isc__gettimeofday(struct timeval * tp,struct timezone * tzp)21 isc__gettimeofday(struct timeval *tp, struct timezone *tzp) {
22 	int res;
23 
24 	res = gettimeofday(tp, tzp);
25 	if (res < 0)
26 		return (res);
27 	if (tp == NULL)
28 		return (res);
29 	if (tp->tv_usec < 0) {
30 		do {
31 			tp->tv_usec += MILLION;
32 			tp->tv_sec--;
33 		} while (tp->tv_usec < 0);
34 		goto log;
35 	} else if (tp->tv_usec > MILLION) {
36 		do {
37 			tp->tv_usec -= MILLION;
38 			tp->tv_sec++;
39 		} while (tp->tv_usec > MILLION);
40 		goto log;
41 	}
42 	return (res);
43  log:
44 	syslog(LOG_ERR, "gettimeofday: tv_usec out of range\n");
45 	return (res);
46 }
47 #else
48 int
gettimeofday(struct timeval * tvp,struct _TIMEZONE * tzp)49 gettimeofday(struct timeval *tvp, struct _TIMEZONE *tzp) {
50 	time_t clock, time(time_t *);
51 
52 	if (time(&clock) == (time_t) -1)
53 		return (-1);
54 	if (tvp) {
55 		tvp->tv_sec = clock;
56 		tvp->tv_usec = 0;
57 	}
58 	if (tzp) {
59 		tzp->tz_minuteswest = 0;
60 		tzp->tz_dsttime = 0;
61 	}
62 	return (0);
63 }
64 #endif /*NEED_GETTIMEOFDAY*/
65 
66 /*! \file */
67