[gpr] Replace a call to localtime with a call to absl::FormatTime.

localtime is not thread-safe, which means that client libraries can suffer from subtle data races.

PiperOrigin-RevId: 670616652
pull/37220/head
Joey Raso 3 months ago committed by Copybara-Service
parent 4fe0033922
commit c0b326baa9
  1. 13
      src/core/util/string.cc

@ -29,6 +29,7 @@
#include <time.h>
#include "absl/strings/str_cat.h"
#include "absl/time/time.h"
#include <grpc/support/alloc.h>
#include <grpc/support/string_util.h>
@ -53,14 +54,14 @@ char* gpr_strdup(const char* src) {
}
std::string gpr_format_timespec(gpr_timespec tm) {
char time_buffer[35];
char ns_buffer[11]; // '.' + 9 digits of precision
struct tm* tm_info = localtime(reinterpret_cast<time_t*>(&tm.tv_sec));
strftime(time_buffer, sizeof(time_buffer), "%Y-%m-%dT%H:%M:%S", tm_info);
snprintf(ns_buffer, 11, ".%09d", tm.tv_nsec);
const std::string time_str =
absl::FormatTime("%Y-%m-%d%ET%H:%M:%S", absl::FromUnixSeconds(tm.tv_sec),
absl::LocalTimeZone());
// This loop trims off trailing zeros by inserting a null character that the
// right point. We iterate in chunks of three because we want 0, 3, 6, or 9
// fractional digits.
char ns_buffer[11]; // '.' + 9 digits of precision
snprintf(ns_buffer, 11, ".%09d", tm.tv_nsec);
for (int i = 7; i >= 1; i -= 3) {
if (ns_buffer[i] == '0' && ns_buffer[i + 1] == '0' &&
ns_buffer[i + 2] == '0') {
@ -73,7 +74,7 @@ std::string gpr_format_timespec(gpr_timespec tm) {
break;
}
}
return absl::StrCat(time_buffer, ns_buffer, "Z");
return absl::StrCat(time_str, ns_buffer, "Z");
}
struct dump_out {

Loading…
Cancel
Save