Skip to content

Commit 452acee

Browse files
author
MarcoFalke
committed
Merge #15266: memory: Construct globals on first use
77777c5 log: Construct global logger on first use (MarcoFalke) Pull request description: The (de)initialization order is not well defined in C++, so generally it is not safe to use globals as the (de/con)structor of one global could use the (de/con)structor of another global before/after it has been (con/de)structed. Specifically this fixes: * `g_logger` might not be initialized on the first use, so do that. (Fixes #15111) Tree-SHA512: eb9c22f4baf31ebc5b0b9ee6a51d1354bae1f0df186cc0ce818b4483c7b5a7f90268d2b549ee96b4c57f8ef36ab239dc6497f74f3e2ef166038f7437c368297d
2 parents bfbe425 + 77777c5 commit 452acee

File tree

6 files changed

+34
-28
lines changed

6 files changed

+34
-28
lines changed

src/httpserver.cpp

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -364,8 +364,8 @@ bool InitHTTPServer()
364364
// Update libevent's log handling. Returns false if our version of
365365
// libevent doesn't support debug logging, in which case we should
366366
// clear the BCLog::LIBEVENT flag.
367-
if (!UpdateHTTPServerLogging(g_logger->WillLogCategory(BCLog::LIBEVENT))) {
368-
g_logger->DisableCategory(BCLog::LIBEVENT);
367+
if (!UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT))) {
368+
LogInstance().DisableCategory(BCLog::LIBEVENT);
369369
}
370370

371371
#ifdef WIN32

src/init.cpp

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -289,7 +289,7 @@ static void HandleSIGTERM(int)
289289

290290
static void HandleSIGHUP(int)
291291
{
292-
g_logger->m_reopen_file = true;
292+
LogInstance().m_reopen_file = true;
293293
}
294294
#else
295295
static BOOL WINAPI consoleCtrlHandler(DWORD dwCtrlType)
@@ -833,17 +833,17 @@ static std::string ResolveErrMsg(const char * const optname, const std::string&
833833
*/
834834
void InitLogging()
835835
{
836-
g_logger->m_print_to_file = !gArgs.IsArgNegated("-debuglogfile");
837-
g_logger->m_file_path = AbsPathForConfigVal(gArgs.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE));
836+
LogInstance().m_print_to_file = !gArgs.IsArgNegated("-debuglogfile");
837+
LogInstance().m_file_path = AbsPathForConfigVal(gArgs.GetArg("-debuglogfile", DEFAULT_DEBUGLOGFILE));
838838

839839
// Add newlines to the logfile to distinguish this execution from the last
840840
// one; called before console logging is set up, so this is only sent to
841841
// debug.log.
842842
LogPrintf("\n\n\n\n\n");
843843

844-
g_logger->m_print_to_console = gArgs.GetBoolArg("-printtoconsole", !gArgs.GetBoolArg("-daemon", false));
845-
g_logger->m_log_timestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
846-
g_logger->m_log_time_micros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
844+
LogInstance().m_print_to_console = gArgs.GetBoolArg("-printtoconsole", !gArgs.GetBoolArg("-daemon", false));
845+
LogInstance().m_log_timestamps = gArgs.GetBoolArg("-logtimestamps", DEFAULT_LOGTIMESTAMPS);
846+
LogInstance().m_log_time_micros = gArgs.GetBoolArg("-logtimemicros", DEFAULT_LOGTIMEMICROS);
847847

848848
fLogIPs = gArgs.GetBoolArg("-logips", DEFAULT_LOGIPS);
849849

@@ -981,7 +981,7 @@ bool AppInitParameterInteraction()
981981
if (std::none_of(categories.begin(), categories.end(),
982982
[](std::string cat){return cat == "0" || cat == "none";})) {
983983
for (const auto& cat : categories) {
984-
if (!g_logger->EnableCategory(cat)) {
984+
if (!LogInstance().EnableCategory(cat)) {
985985
InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debug", cat));
986986
}
987987
}
@@ -990,7 +990,7 @@ bool AppInitParameterInteraction()
990990

991991
// Now remove the logging categories which were explicitly excluded
992992
for (const std::string& cat : gArgs.GetArgs("-debugexclude")) {
993-
if (!g_logger->DisableCategory(cat)) {
993+
if (!LogInstance().DisableCategory(cat)) {
994994
InitWarning(strprintf(_("Unsupported logging category %s=%s."), "-debugexclude", cat));
995995
}
996996
}
@@ -1197,19 +1197,19 @@ bool AppInitMain(InitInterfaces& interfaces)
11971197
#ifndef WIN32
11981198
CreatePidFile(GetPidFile(), getpid());
11991199
#endif
1200-
if (g_logger->m_print_to_file) {
1201-
if (gArgs.GetBoolArg("-shrinkdebugfile", g_logger->DefaultShrinkDebugFile())) {
1200+
if (LogInstance().m_print_to_file) {
1201+
if (gArgs.GetBoolArg("-shrinkdebugfile", LogInstance().DefaultShrinkDebugFile())) {
12021202
// Do this first since it both loads a bunch of debug.log into memory,
12031203
// and because this needs to happen before any other debug.log printing
1204-
g_logger->ShrinkDebugFile();
1204+
LogInstance().ShrinkDebugFile();
12051205
}
1206-
if (!g_logger->OpenDebugLog()) {
1206+
if (!LogInstance().OpenDebugLog()) {
12071207
return InitError(strprintf("Could not open debug log file %s",
1208-
g_logger->m_file_path.string()));
1208+
LogInstance().m_file_path.string()));
12091209
}
12101210
}
12111211

1212-
if (!g_logger->m_log_timestamps)
1212+
if (!LogInstance().m_log_timestamps)
12131213
LogPrintf("Startup time: %s\n", FormatISO8601DateTime(GetTime()));
12141214
LogPrintf("Default data directory %s\n", GetDefaultDataDir().string());
12151215
LogPrintf("Using data directory %s\n", GetDataDir().string());

src/interfaces/node.cpp

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ class NodeImpl : public Node
6767
void initLogging() override { InitLogging(); }
6868
void initParameterInteraction() override { InitParameterInteraction(); }
6969
std::string getWarnings(const std::string& type) override { return GetWarnings(type); }
70-
uint32_t getLogCategories() override { return g_logger->GetCategoryMask(); }
70+
uint32_t getLogCategories() override { return LogInstance().GetCategoryMask(); }
7171
bool baseInitialize() override
7272
{
7373
return AppInitBasicSetup() && AppInitParameterInteraction() && AppInitSanityChecks() &&

src/logging.cpp

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,8 @@
88

99
const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
1010

11+
BCLog::Logger& LogInstance()
12+
{
1113
/**
1214
* NOTE: the logger instances is leaked on exit. This is ugly, but will be
1315
* cleaned up by the OS/libc. Defining a logger as a global object doesn't work
@@ -17,11 +19,15 @@ const char * const DEFAULT_DEBUGLOGFILE = "debug.log";
1719
* access the logger. When the shutdown sequence is fully audited and tested,
1820
* explicit destruction of these objects can be implemented by changing this
1921
* from a raw pointer to a std::unique_ptr.
22+
* Since the destructor is never called, the logger and all its members must
23+
* have a trivial destructor.
2024
*
2125
* This method of initialization was originally introduced in
2226
* ee3374234c60aba2cc4c5cd5cac1c0aefc2d817c.
2327
*/
24-
BCLog::Logger* const g_logger = new BCLog::Logger();
28+
static BCLog::Logger* g_logger{new BCLog::Logger()};
29+
return *g_logger;
30+
}
2531

2632
bool fLogIPs = DEFAULT_LOGIPS;
2733

src/logging.h

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -108,12 +108,12 @@ namespace BCLog {
108108

109109
} // namespace BCLog
110110

111-
extern BCLog::Logger* const g_logger;
111+
BCLog::Logger& LogInstance();
112112

113113
/** Return true if log accepts specified category */
114114
static inline bool LogAcceptCategory(BCLog::LogFlags category)
115115
{
116-
return g_logger->WillLogCategory(category);
116+
return LogInstance().WillLogCategory(category);
117117
}
118118

119119
/** Returns a string with the log categories. */
@@ -132,15 +132,15 @@ bool GetLogCategory(BCLog::LogFlags& flag, const std::string& str);
132132
template <typename... Args>
133133
static inline void LogPrintf(const char* fmt, const Args&... args)
134134
{
135-
if (g_logger->Enabled()) {
135+
if (LogInstance().Enabled()) {
136136
std::string log_msg;
137137
try {
138138
log_msg = tfm::format(fmt, args...);
139139
} catch (tinyformat::format_error& fmterr) {
140140
/* Original format string will have newline so don't add one here */
141141
log_msg = "Error \"" + std::string(fmterr.what()) + "\" while formatting log message: " + fmt;
142142
}
143-
g_logger->LogPrintStr(log_msg);
143+
LogInstance().LogPrintStr(log_msg);
144144
}
145145
}
146146

src/rpc/misc.cpp

Lines changed: 6 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -366,9 +366,9 @@ static void EnableOrDisableLogCategories(UniValue cats, bool enable) {
366366

367367
bool success;
368368
if (enable) {
369-
success = g_logger->EnableCategory(cat);
369+
success = LogInstance().EnableCategory(cat);
370370
} else {
371-
success = g_logger->DisableCategory(cat);
371+
success = LogInstance().DisableCategory(cat);
372372
}
373373

374374
if (!success) {
@@ -415,14 +415,14 @@ UniValue logging(const JSONRPCRequest& request)
415415
}.ToString());
416416
}
417417

418-
uint32_t original_log_categories = g_logger->GetCategoryMask();
418+
uint32_t original_log_categories = LogInstance().GetCategoryMask();
419419
if (request.params[0].isArray()) {
420420
EnableOrDisableLogCategories(request.params[0], true);
421421
}
422422
if (request.params[1].isArray()) {
423423
EnableOrDisableLogCategories(request.params[1], false);
424424
}
425-
uint32_t updated_log_categories = g_logger->GetCategoryMask();
425+
uint32_t updated_log_categories = LogInstance().GetCategoryMask();
426426
uint32_t changed_log_categories = original_log_categories ^ updated_log_categories;
427427

428428
// Update libevent logging if BCLog::LIBEVENT has changed.
@@ -431,8 +431,8 @@ UniValue logging(const JSONRPCRequest& request)
431431
// Throw an error if the user has explicitly asked to change only the libevent
432432
// flag and it failed.
433433
if (changed_log_categories & BCLog::LIBEVENT) {
434-
if (!UpdateHTTPServerLogging(g_logger->WillLogCategory(BCLog::LIBEVENT))) {
435-
g_logger->DisableCategory(BCLog::LIBEVENT);
434+
if (!UpdateHTTPServerLogging(LogInstance().WillLogCategory(BCLog::LIBEVENT))) {
435+
LogInstance().DisableCategory(BCLog::LIBEVENT);
436436
if (changed_log_categories == BCLog::LIBEVENT) {
437437
throw JSONRPCError(RPC_INVALID_PARAMETER, "libevent logging cannot be updated when using libevent before v2.1.1.");
438438
}

0 commit comments

Comments
 (0)