From f3d4c1165d9f3645c13d15142cc902d2cf7532cc Mon Sep 17 00:00:00 2001 From: Marcin Serwin Date: Mon, 17 Feb 2025 23:54:13 +0100 Subject: [PATCH] fix: copy the string returned by getenv (#3264) --- src/builtin.c | 7 +++++-- tests/shtest | 8 ++++++++ 2 files changed, 13 insertions(+), 2 deletions(-) diff --git a/src/builtin.c b/src/builtin.c index fc06d949..ad14da25 100644 --- a/src/builtin.c +++ b/src/builtin.c @@ -1474,8 +1474,10 @@ static time_t my_mktime(struct tm *tm) { if (tz != NULL) setenv("TZ", "", 1); time_t t = mktime(tm); - if (tz != NULL) + if (tz != NULL) { setenv("TZ", tz, 1); + free(tz); + } return t; #endif } @@ -1762,13 +1764,14 @@ static jv f_strftime(jq_state *jq, jv a, jv b) { /* Apple Libc (as of version 1669.40.2) contains a bug which causes it to * ignore the `tm.tm_gmtoff` in favor of the global timezone. To print the * proper timezone offset we temporarily switch the TZ to UTC. */ - char *tz = getenv("TZ"); + char *tz = (tz = getenv("TZ")) != NULL ? strdup(tz) : NULL; setenv("TZ", "UTC", 1); #endif size_t n = strftime(buf, alloced, fmt, &tm); #ifdef __APPLE__ if (tz) { setenv("TZ", tz, 1); + free(tz); } else { unsetenv("TZ"); } diff --git a/tests/shtest b/tests/shtest index efb63771..e8c1580f 100755 --- a/tests/shtest +++ b/tests/shtest @@ -728,6 +728,14 @@ if ! $msys && ! $mingw; then echo "Incorrectly formatted universal time" exit 1 fi + + if ! r=$(TZ=Etc/GMT+7 $JQ -nc '1731627341 | .,. | [strftime("%FT%T"),strflocaltime("%FT%T%z")]' +) \ + || [ "$r" != '["2024-11-14T23:35:41","2024-11-14T16:35:41-0700"] +["2024-11-14T23:35:41","2024-11-14T16:35:41-0700"]' ]; then + echo "strftime or strftimelocal are not pure functions" + exit 1 + fi fi exit 0