[review v5] Use ctime_r and localtime_r for threadsafety

Christian Biesinger (Code Review)
2019-11-11T22:27:59Z

Use ctime_r and localtime_r for threadsafety

To make these calls threadsafe. localtime_r is provided by gnulib if
necessary, and for ctime_r we can just use it because it is in a linux-
specific file.

gdb/ChangeLog:

2019-10-31 Christian Biesinger <cbiesinger@google.com>

* maint.c (scoped_command_stats::print_time): Use localtime_r
instead of localtime (provided through gnulib if necessary).
* nat/linux-osdata.c (time_from_time_t): Use ctime_r instead
of ctime.

Change-Id: I329bbdc39d5b576f51859ba00f1617e024c30cbd
---
M gdb/maint.c
M gdb/nat/linux-osdata.c
2 files changed, 8 insertions(+), 3 deletions(-)

diff --git a/gdb/maint.c b/gdb/maint.c
index ec9f4ab..a253584 100644
--- a/gdb/maint.c
+++ b/gdb/maint.c
@@ -1039,10 +1039,11 @@
auto millis = ticks % 1000;

std::time_t as_time = system_clock::to_time_t (now);
- struct tm *tm = localtime (&as_time);
+ struct tm tm;
+ localtime_r (&as_time, &tm);

char out[100];
- strftime (out, sizeof (out), "%F %H:%M:%S", tm);
+ strftime (out, sizeof (out), "%F %H:%M:%S", &tm);

printf_unfiltered ("%s.%03d - %s\n", out, (int) millis, msg);
}
diff --git a/gdb/nat/linux-osdata.c b/gdb/nat/linux-osdata.c
index 84357e2..a0b43c6 100644
--- a/gdb/nat/linux-osdata.c
+++ b/gdb/nat/linux-osdata.c
@@ -913,7 +913,11 @@
{
time_t t = (time_t) seconds;

- strncpy (time, ctime (&t), maxlen);
+ /* Per the ctime_r manpage, this buffer needs to be at least 26
+ characters long. */
+ char buf[30];
+ const char *time_str = ctime_r (&t, buf);
+ strncpy (time, time_str, maxlen);
time[maxlen - 1] = '\0';
}
}

--
Gerrit-Project: binutils-gdb
Gerrit-Branch: master
Gerrit-Change-Id: I329bbdc39d5b576f51859ba00f1617e024c30cbd
Gerrit-Change-Number: 475
Gerrit-PatchSet: 5
Gerrit-Owner: Christian Biesinger <cbiesinger@google.com>
Gerrit-Reviewer: Christian Biesinger <cbiesinger@google.com>
Gerrit-Reviewer: Kevin Buettner <kevinb@redhat.com>
Gerrit-MessageType: newpatchset