From 28ef5146ba4e366bf1d8be664c3cd0fa71f42d56 Mon Sep 17 00:00:00 2001 From: Peter Nelson Date: Sat, 30 Dec 2023 00:07:51 +0000 Subject: [PATCH] Fix #11646: Non-thread safe shared buffer returned from GetLogPrefix(). Return string from GetLogPrefix instead of shared string's buffer. --- src/console.cpp | 7 +++---- src/debug.cpp | 14 ++++++-------- src/debug.h | 2 +- 3 files changed, 10 insertions(+), 13 deletions(-) diff --git a/src/console.cpp b/src/console.cpp index becbcd644f..baeb893e83 100644 --- a/src/console.cpp +++ b/src/console.cpp @@ -51,10 +51,9 @@ static void IConsoleWriteToLogFile(const std::string &string) { if (_iconsole_output_file != nullptr) { /* if there is an console output file ... also print it there */ - const char *header = GetLogPrefix(); - if ((strlen(header) != 0 && fwrite(header, strlen(header), 1, _iconsole_output_file) != 1) || - fwrite(string.c_str(), string.size(), 1, _iconsole_output_file) != 1 || - fwrite("\n", 1, 1, _iconsole_output_file) != 1) { + try { + fmt::print(_iconsole_output_file, "{}{}\n", GetLogPrefix(), string); + } catch (const std::system_error &) { fclose(_iconsole_output_file); _iconsole_output_file = nullptr; IConsolePrint(CC_ERROR, "Cannot write to console log file; closing the log file."); diff --git a/src/debug.cpp b/src/debug.cpp index 6bc66532da..fba8111dd6 100644 --- a/src/debug.cpp +++ b/src/debug.cpp @@ -219,18 +219,16 @@ std::string GetDebugString() /** * Get the prefix for logs; if show_date_in_logs is enabled it returns - * the date, otherwise it returns nothing. - * @return the prefix for logs (do not free), never nullptr + * the date, otherwise it returns an empty string. + * @return the prefix for logs. */ -const char *GetLogPrefix() +std::string GetLogPrefix() { - static std::string _log_prefix; + std::string log_prefix; if (_settings_client.gui.show_date_in_logs) { - _log_prefix = fmt::format("[{:%Y-%m-%d %H:%M:%S}] ", fmt::localtime(time(nullptr))); - } else { - _log_prefix.clear(); + log_prefix = fmt::format("[{:%Y-%m-%d %H:%M:%S}] ", fmt::localtime(time(nullptr))); } - return _log_prefix.c_str(); + return log_prefix; } /** diff --git a/src/debug.h b/src/debug.h index 60725df8e5..a7e6300683 100644 --- a/src/debug.h +++ b/src/debug.h @@ -120,7 +120,7 @@ std::string GetDebugString(); void ShowInfoI(const std::string &str); #define ShowInfo(format_string, ...) ShowInfoI(fmt::format(FMT_STRING(format_string), ## __VA_ARGS__)) -const char *GetLogPrefix(); +std::string GetLogPrefix(); void DebugSendRemoteMessages(); void DebugReconsiderSendRemoteMessages();