Skip to content

Commit e2d680a

Browse files
util: Add SignalInterrupt class and use in shutdown.cpp
This change helps generalize shutdown code so an interrupt can be provided to libbitcoinkernel callers. This may also be useful to eventually de-globalize all of the shutdown code. Co-authored-by: Russell Yanofsky <[email protected]> Co-authored-by: TheCharlatan <[email protected]>
1 parent d9c7c2f commit e2d680a

File tree

10 files changed

+175
-65
lines changed

10 files changed

+175
-65
lines changed

src/Makefile.am

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -310,6 +310,7 @@ BITCOIN_CORE_H = \
310310
util/readwritefile.h \
311311
util/result.h \
312312
util/serfloat.h \
313+
util/signalinterrupt.h \
313314
util/sock.h \
314315
util/spanparsing.h \
315316
util/string.h \
@@ -733,6 +734,7 @@ libbitcoin_util_a_SOURCES = \
733734
util/moneystr.cpp \
734735
util/rbf.cpp \
735736
util/readwritefile.cpp \
737+
util/signalinterrupt.cpp \
736738
util/thread.cpp \
737739
util/threadinterrupt.cpp \
738740
util/threadnames.cpp \
@@ -972,6 +974,7 @@ libbitcoinkernel_la_SOURCES = \
972974
util/moneystr.cpp \
973975
util/rbf.cpp \
974976
util/serfloat.cpp \
977+
util/signalinterrupt.cpp \
975978
util/strencodings.cpp \
976979
util/string.cpp \
977980
util/syserror.cpp \

src/init.cpp

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -812,9 +812,7 @@ bool AppInitBasicSetup(const ArgsManager& args, std::atomic<int>& exit_status)
812812
// Enable heap terminate-on-corruption
813813
HeapSetInformation(nullptr, HeapEnableTerminationOnCorruption, nullptr, 0);
814814
#endif
815-
if (!InitShutdownState(exit_status)) {
816-
return InitError(Untranslated("Initializing wait-for-shutdown state failed."));
817-
}
815+
InitShutdownState(exit_status);
818816

819817
if (!SetupNetworking()) {
820818
return InitError(Untranslated("Initializing networking failed."));

src/kernel/context.cpp

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,9 +14,12 @@
1414

1515

1616
namespace kernel {
17+
Context* g_context;
1718

1819
Context::Context()
1920
{
21+
assert(!g_context);
22+
g_context = this;
2023
std::string sha256_algo = SHA256AutoDetect();
2124
LogPrintf("Using the '%s' SHA256 implementation\n", sha256_algo);
2225
RandomInit();
@@ -26,6 +29,8 @@ Context::Context()
2629
Context::~Context()
2730
{
2831
ECC_Stop();
32+
assert(g_context);
33+
g_context = nullptr;
2934
}
3035

3136
} // namespace kernel

src/kernel/context.h

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,8 @@
55
#ifndef BITCOIN_KERNEL_CONTEXT_H
66
#define BITCOIN_KERNEL_CONTEXT_H
77

8+
#include <util/signalinterrupt.h>
9+
810
#include <memory>
911

1012
namespace kernel {
@@ -16,12 +18,24 @@ namespace kernel {
1618
//! State stored directly in this struct should be simple. More complex state
1719
//! should be stored to std::unique_ptr members pointing to opaque types.
1820
struct Context {
21+
//! Interrupt object that can be used to stop long-running kernel operations.
22+
util::SignalInterrupt interrupt;
23+
1924
//! Declare default constructor and destructor that are not inline, so code
2025
//! instantiating the kernel::Context struct doesn't need to #include class
2126
//! definitions for all the unique_ptr members.
2227
Context();
2328
~Context();
2429
};
30+
31+
//! Global pointer to kernel::Context for legacy code. New code should avoid
32+
//! using this, and require state it needs to be passed to it directly.
33+
//!
34+
//! Having this pointer is useful because it allows state be moved out of global
35+
//! variables into the kernel::Context struct before all global references to
36+
//! that state are removed. This allows the global references to be removed
37+
//! incrementally, instead of all at once.
38+
extern Context* g_context;
2539
} // namespace kernel
2640

2741
#endif // BITCOIN_KERNEL_CONTEXT_H

src/qt/test/apptests.cpp

Lines changed: 0 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -86,7 +86,6 @@ void AppTests::appTests()
8686

8787
// Reset global state to avoid interfering with later tests.
8888
LogInstance().DisconnectTestLogger();
89-
AbortShutdown();
9089
}
9190

9291
//! Entry point for BitcoinGUI tests.

src/shutdown.cpp

Lines changed: 14 additions & 55 deletions
Original file line numberDiff line numberDiff line change
@@ -9,17 +9,15 @@
99
#include <config/bitcoin-config.h>
1010
#endif
1111

12+
#include <kernel/context.h>
1213
#include <logging.h>
1314
#include <node/interface_ui.h>
1415
#include <util/check.h>
15-
#include <util/tokenpipe.h>
16+
#include <util/signalinterrupt.h>
1617
#include <warnings.h>
1718

18-
#include <assert.h>
1919
#include <atomic>
20-
#ifdef WIN32
21-
#include <condition_variable>
22-
#endif
20+
#include <cassert>
2321

2422
static std::atomic<int>* g_exit_status{nullptr};
2523

@@ -36,76 +34,37 @@ bool AbortNode(const std::string& strMessage, bilingual_str user_message)
3634
return false;
3735
}
3836

39-
static std::atomic<bool> fRequestShutdown(false);
40-
#ifdef WIN32
41-
/** On windows it is possible to simply use a condition variable. */
42-
std::mutex g_shutdown_mutex;
43-
std::condition_variable g_shutdown_cv;
44-
#else
45-
/** On UNIX-like operating systems use the self-pipe trick.
46-
*/
47-
static TokenPipeEnd g_shutdown_r;
48-
static TokenPipeEnd g_shutdown_w;
49-
#endif
50-
51-
bool InitShutdownState(std::atomic<int>& exit_status)
37+
void InitShutdownState(std::atomic<int>& exit_status)
5238
{
5339
g_exit_status = &exit_status;
54-
#ifndef WIN32
55-
std::optional<TokenPipe> pipe = TokenPipe::Make();
56-
if (!pipe) return false;
57-
g_shutdown_r = pipe->TakeReadEnd();
58-
g_shutdown_w = pipe->TakeWriteEnd();
59-
#endif
60-
return true;
6140
}
6241

6342
void StartShutdown()
6443
{
65-
#ifdef WIN32
66-
std::unique_lock<std::mutex> lk(g_shutdown_mutex);
67-
fRequestShutdown = true;
68-
g_shutdown_cv.notify_one();
69-
#else
70-
// This must be reentrant and safe for calling in a signal handler, so using a condition variable is not safe.
71-
// Make sure that the token is only written once even if multiple threads call this concurrently or in
72-
// case of a reentrant signal.
73-
if (!fRequestShutdown.exchange(true)) {
74-
// Write an arbitrary byte to the write end of the shutdown pipe.
75-
int res = g_shutdown_w.TokenWrite('x');
76-
if (res != 0) {
77-
LogPrintf("Sending shutdown token failed\n");
78-
assert(0);
79-
}
44+
try {
45+
Assert(kernel::g_context)->interrupt();
46+
} catch (const std::system_error&) {
47+
LogPrintf("Sending shutdown token failed\n");
48+
assert(0);
8049
}
81-
#endif
8250
}
8351

8452
void AbortShutdown()
8553
{
86-
if (fRequestShutdown) {
87-
// Cancel existing shutdown by waiting for it, this will reset condition flags and remove
88-
// the shutdown token from the pipe.
89-
WaitForShutdown();
90-
}
91-
fRequestShutdown = false;
54+
Assert(kernel::g_context)->interrupt.reset();
9255
}
9356

9457
bool ShutdownRequested()
9558
{
96-
return fRequestShutdown;
59+
return bool{Assert(kernel::g_context)->interrupt};
9760
}
9861

9962
void WaitForShutdown()
10063
{
101-
#ifdef WIN32
102-
std::unique_lock<std::mutex> lk(g_shutdown_mutex);
103-
g_shutdown_cv.wait(lk, [] { return fRequestShutdown.load(); });
104-
#else
105-
int res = g_shutdown_r.TokenRead();
106-
if (res != 'x') {
64+
try {
65+
Assert(kernel::g_context)->interrupt.wait();
66+
} catch (const std::system_error&) {
10767
LogPrintf("Reading shutdown token failed\n");
10868
assert(0);
10969
}
110-
#endif
11170
}

src/shutdown.h

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ bool AbortNode(const std::string& strMessage, bilingual_str user_message = bilin
1616
/** Initialize shutdown state. This must be called before using either StartShutdown(),
1717
* AbortShutdown() or WaitForShutdown(). Calling ShutdownRequested() is always safe.
1818
*/
19-
bool InitShutdownState(std::atomic<int>& exit_status);
19+
void InitShutdownState(std::atomic<int>& exit_status);
2020

2121
/** Request shutdown of the application. */
2222
void StartShutdown();

src/util/signalinterrupt.cpp

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
// Copyright (c) 2022 The Bitcoin Core developers
2+
// Distributed under the MIT software license, see the accompanying
3+
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4+
5+
#include <util/signalinterrupt.h>
6+
7+
#ifdef WIN32
8+
#include <mutex>
9+
#else
10+
#include <util/tokenpipe.h>
11+
#endif
12+
13+
#include <ios>
14+
#include <optional>
15+
16+
namespace util {
17+
18+
SignalInterrupt::SignalInterrupt() : m_flag{false}
19+
{
20+
#ifndef WIN32
21+
std::optional<TokenPipe> pipe = TokenPipe::Make();
22+
if (!pipe) throw std::ios_base::failure("Could not create TokenPipe");
23+
m_pipe_r = pipe->TakeReadEnd();
24+
m_pipe_w = pipe->TakeWriteEnd();
25+
#endif
26+
}
27+
28+
SignalInterrupt::operator bool() const
29+
{
30+
return m_flag;
31+
}
32+
33+
void SignalInterrupt::reset()
34+
{
35+
// Cancel existing interrupt by waiting for it, this will reset condition flags and remove
36+
// the token from the pipe.
37+
if (*this) wait();
38+
m_flag = false;
39+
}
40+
41+
void SignalInterrupt::operator()()
42+
{
43+
#ifdef WIN32
44+
std::unique_lock<std::mutex> lk(m_mutex);
45+
m_flag = true;
46+
m_cv.notify_one();
47+
#else
48+
// This must be reentrant and safe for calling in a signal handler, so using a condition variable is not safe.
49+
// Make sure that the token is only written once even if multiple threads call this concurrently or in
50+
// case of a reentrant signal.
51+
if (!m_flag.exchange(true)) {
52+
// Write an arbitrary byte to the write end of the pipe.
53+
int res = m_pipe_w.TokenWrite('x');
54+
if (res != 0) {
55+
throw std::ios_base::failure("Could not write interrupt token");
56+
}
57+
}
58+
#endif
59+
}
60+
61+
void SignalInterrupt::wait()
62+
{
63+
#ifdef WIN32
64+
std::unique_lock<std::mutex> lk(m_mutex);
65+
m_cv.wait(lk, [this] { return m_flag.load(); });
66+
#else
67+
int res = m_pipe_r.TokenRead();
68+
if (res != 'x') {
69+
throw std::ios_base::failure("Did not read expected interrupt token");
70+
}
71+
#endif
72+
}
73+
74+
} // namespace util

src/util/signalinterrupt.h

Lines changed: 52 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,52 @@
1+
// Copyright (c) 2023 The Bitcoin Core developers
2+
// Distributed under the MIT software license, see the accompanying
3+
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
4+
5+
#ifndef BITCOIN_UTIL_SIGNALINTERRUPT_H
6+
#define BITCOIN_UTIL_SIGNALINTERRUPT_H
7+
8+
#ifdef WIN32
9+
#include <condition_variable>
10+
#include <mutex>
11+
#else
12+
#include <util/tokenpipe.h>
13+
#endif
14+
15+
#include <atomic>
16+
#include <cstdlib>
17+
18+
namespace util {
19+
/**
20+
* Helper class that manages an interrupt flag, and allows a thread or
21+
* signal to interrupt another thread.
22+
*
23+
* This class is safe to be used in a signal handler. If sending an interrupt
24+
* from a signal handler is not necessary, the more lightweight \ref
25+
* CThreadInterrupt class can be used instead.
26+
*/
27+
28+
class SignalInterrupt
29+
{
30+
public:
31+
SignalInterrupt();
32+
explicit operator bool() const;
33+
void operator()();
34+
void reset();
35+
void wait();
36+
37+
private:
38+
std::atomic<bool> m_flag;
39+
40+
#ifndef WIN32
41+
// On UNIX-like operating systems use the self-pipe trick.
42+
TokenPipeEnd m_pipe_r;
43+
TokenPipeEnd m_pipe_w;
44+
#else
45+
// On windows use a condition variable, since we don't have any signals there
46+
std::mutex m_mutex;
47+
std::condition_variable m_cv;
48+
#endif
49+
};
50+
} // namespace util
51+
52+
#endif // BITCOIN_UTIL_SIGNALINTERRUPT_H

src/util/threadinterrupt.h

Lines changed: 11 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -12,11 +12,17 @@
1212
#include <chrono>
1313
#include <condition_variable>
1414

15-
/*
16-
A helper class for interruptible sleeps. Calling operator() will interrupt
17-
any current sleep, and after that point operator bool() will return true
18-
until reset.
19-
*/
15+
/**
16+
* A helper class for interruptible sleeps. Calling operator() will interrupt
17+
* any current sleep, and after that point operator bool() will return true
18+
* until reset.
19+
*
20+
* This class should not be used in a signal handler. It uses thread
21+
* synchronization primitives that are not safe to use with signals. If sending
22+
* an interrupt from a signal handler is necessary, the \ref SignalInterrupt
23+
* class can be used instead.
24+
*/
25+
2026
class CThreadInterrupt
2127
{
2228
public:

0 commit comments

Comments
 (0)