Skip to content

Commit

Permalink
pool: don't trample upon users of localtime().
Browse files Browse the repository at this point in the history
The function is not thread safe -- and even in single-threaded code, the
user might be using the value with a library call in between.
  • Loading branch information
kilobyte committed Aug 13, 2021
1 parent 924d05f commit e552773
Show file tree
Hide file tree
Showing 4 changed files with 20 additions and 10 deletions.
16 changes: 13 additions & 3 deletions src/core/util.c
Original file line number Diff line number Diff line change
Expand Up @@ -395,14 +395,24 @@ util_concat_str(const char *s1, const char *s2)
* in such cases.
*/
struct tm *
util_localtime(const time_t *timep)
util_localtime(const time_t *timep, struct tm *tm)
{
#ifdef _WIN32
/* C11 has localtime_s(), but Microsoft's version reverses the args */
int err = localtime_s(tm, timep);
if (err) {
errno = err;
return NULL;
} else {
return tm;
}
#else
int oerrno = errno;
struct tm *tm = localtime(timep);
tm = localtime_r(timep, tm);
if (tm != NULL)
errno = oerrno;

return tm;
#endif
}

/*
Expand Down
2 changes: 1 addition & 1 deletion src/core/util.h
Original file line number Diff line number Diff line change
Expand Up @@ -95,7 +95,7 @@ char *util_part_realpath(const char *path);
int util_compare_file_inodes(const char *path1, const char *path2);
void *util_aligned_malloc(size_t alignment, size_t size);
void util_aligned_free(void *ptr);
struct tm *util_localtime(const time_t *timep);
struct tm *util_localtime(const time_t *timep, struct tm *tm);
int util_safe_strcpy(char *dst, const char *src, size_t max_length);
void util_emit_log(const char *lib, const char *func, int order);
char *util_readline(FILE *fh);
Expand Down
6 changes: 3 additions & 3 deletions src/libpmempool/check_util.c
Original file line number Diff line number Diff line change
Expand Up @@ -628,10 +628,10 @@ const char *
check_get_time_str(time_t time)
{
static char str_buff[STR_MAX] = {0, };
struct tm *tm = util_localtime(&time);
struct tm tm;

if (tm)
strftime(str_buff, STR_MAX, TIME_STR_FMT, tm);
if (util_localtime(&time, &tm))
strftime(str_buff, STR_MAX, TIME_STR_FMT, &tm);
else {
int ret = util_snprintf(str_buff, STR_MAX, "unknown");
if (ret < 0) {
Expand Down
6 changes: 3 additions & 3 deletions src/tools/pmempool/output.c
Original file line number Diff line number Diff line change
Expand Up @@ -348,10 +348,10 @@ const char *
out_get_time_str(time_t time)
{
static char str_buff[STR_MAX] = {0, };
struct tm *tm = util_localtime(&time);
struct tm tm;

if (tm) {
strftime(str_buff, STR_MAX, TIME_STR_FMT, tm);
if (util_localtime(&time, &tm)) {
strftime(str_buff, STR_MAX, TIME_STR_FMT, &tm);
} else {
int ret = util_snprintf(str_buff, STR_MAX, "unknown");
if (ret < 0)
Expand Down

0 comments on commit e552773

Please sign in to comment.