Skip to content

Commit

Permalink
Handle various time_t sizes in printf and scanf
Browse files Browse the repository at this point in the history
The members of the timeval struct are both signed (defined by POSIX)
and typically both 64 bits on a system where time_t is 64 bits.  This
is possible also on 32 bit systems where time_t is larger to handle
the 2038 problem.

It's practically impossible to find a type and printf format that
works even on all glibc systems.  Play it safe and always use printf
with intmax_t and explict int64_t variables for scanf.
  • Loading branch information
snogge authored and garlick committed Dec 29, 2024
1 parent 1606e4c commit eae17bc
Show file tree
Hide file tree
Showing 3 changed files with 14 additions and 6 deletions.
5 changes: 3 additions & 2 deletions libnpfs/conn.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdarg.h>
#include <errno.h>
#include <pthread.h>
Expand Down Expand Up @@ -132,8 +133,8 @@ _debug_trace (Npsrv *srv, Npfcall *fc)
(void)gettimeofday(&b, NULL);
(void)gettimeofday(&a, NULL);
timersub(&a, &b, &c);
np_logmsg(srv, "[%lu.%-3lu] %s",
c.tv_sec, c.tv_usec/1000, s);
np_logmsg(srv, "[%"PRIdMAX".%-3"PRIdMAX"] %s",
(intmax_t)c.tv_sec, (intmax_t)c.tv_usec/1000, s);
} else
np_logmsg(srv, "%s", s);
}
Expand Down
7 changes: 4 additions & 3 deletions libnpfs/ctl.c
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
#include <stdio.h>
#include <string.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdarg.h>
#include <pthread.h>
#include <errno.h>
Expand Down Expand Up @@ -291,9 +292,9 @@ _ctl_get_date (char *name, void *a)
np_uerror (errno);
goto error;
}
if (aspf (&s, &len, "%lu.%lu %d.%d\n",
tv.tv_sec, tv.tv_usec,
tz.tz_minuteswest, tz.tz_dsttime) < 0) {
if (aspf (&s, &len, "%"PRIdMAX".%"PRIdMAX" %d.%d\n",
(uintmax_t)tv.tv_sec, (uintmax_t)tv.tv_usec,
tz.tz_minuteswest, tz.tz_dsttime) < 0) {
np_uerror (ENOMEM);
goto error;
}
Expand Down
8 changes: 7 additions & 1 deletion utils/dioddate.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
#include <unistd.h>
#include <stdlib.h>
#include <stdint.h>
#include <inttypes.h>
#include <stdarg.h>
#include <stdio.h>
#if HAVE_GETOPT_H
Expand Down Expand Up @@ -142,11 +143,16 @@ main (int argc, char *argv[])
errn (np_rerror (), "error reading date");
goto done;
}
if (sscanf (buf, "%lu.%lu %d.%d", &tv.tv_sec, &tv.tv_usec,

int64_t sec = 0, usec = 0;
if (sscanf (buf, "%"SCNd64".%"SCNd64" %d.%d", &sec, &usec,
&tz.tz_minuteswest, &tz.tz_dsttime) != 4) {
msg ("error scanning returned date: %s", buf);
goto done;
}
tv.tv_sec = sec;
tv.tv_usec = usec;

if (Sopt) {
if (settimeofday (&tv, &tz) < 0)
err_exit ("settimeofday");
Expand Down

0 comments on commit eae17bc

Please sign in to comment.