From dca583ac625cbbc21b5a795ef36d1f90fabbcce7 Mon Sep 17 00:00:00 2001 From: Paul Eggert Date: Sun, 9 Aug 2020 10:42:02 -0700 Subject: [PATCH 25/47] date: redo strftime buffer-exhaustion check MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Suggested by Robert Elz in: https://mm.icann.org/pipermail/tz/2020-August/029193.html * date.c (main, display): Record the format’s leading '+' too. (timeout): Format the leading '+' too; just don’t output it. This simplifies checking for buffer exhaustion, given strftime’s somewhat-lame API. --- date.c | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/date.c b/date.c index 2cc533f..ce63bf3 100644 --- a/date.c +++ b/date.c @@ -112,7 +112,7 @@ main(const int argc, char *argv[]) cp = argv[optind++]; if (*cp == '+') if (format == NULL) - format = cp + 1; + format = cp; else { fprintf(stderr, _("date: error: multiple formats in command line\n")); @@ -186,7 +186,7 @@ display(char const *format, time_t now) errensure(); return; } - timeout(stdout, format ? format : "%+", tmp); + timeout(stdout, format ? format : "+%+", tmp); putchar('\n'); fflush(stdout); fflush(stderr); @@ -207,8 +207,6 @@ timeout(FILE *fp, char const *format, struct tm const *tmp) size_t size; struct tm tm; - if (*format == '\0') - return; if (!tmp) { fprintf(stderr, _("date: error: time out of range\n")); errensure(); @@ -225,13 +223,12 @@ timeout(FILE *fp, char const *format, struct tm const *tmp) errensure(); exit(retval); } - cp[0] = '\1'; result = strftime(cp, size, format, tmp); - if (result != 0 || cp[0] == '\0') + if (result != 0) break; size += INCR; cp = realloc(cp, size); } - fwrite(cp, 1, result, fp); + fwrite(cp + 1, 1, result - 1, fp); free(cp); } -- 1.8.3.1