summaryrefslogtreecommitdiffstats
path: root/src/common-lib/unixsignalhandler.cpp
blob: e25115ee144b623f0f078eccb8600e9c4b1a6295 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
// Copyright (C) 2021 The Qt Company Ltd.
// Copyright (C) 2019 Luxoft Sweden AB
// Copyright (C) 2018 Pelagicore AG
// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR GPL-3.0-only

#include "unixsignalhandler.h"
#include "logging.h"

#include <QSocketNotifier>
#include <QCoreApplication>

#include <cerrno>

#if defined(Q_OS_WIN)
#  include <windows.h>
#  include <synchapi.h>
#else
#  include <sys/mman.h>
#endif

#if defined(Q_OS_UNIX) && !defined(Q_OS_QNX)
#  define AM_POSIX_SIGNALS
#endif

QT_BEGIN_NAMESPACE_AM

// sigmask() is not available on Windows
UnixSignalHandler::am_sigmask_t UnixSignalHandler::am_sigmask(int sig)
{
    return ((am_sigmask_t(1)) << (((sig) - 1) % int(8 * sizeof(am_sigmask_t))));
}

UnixSignalHandler *UnixSignalHandler::s_instance = nullptr;

UnixSignalHandler::UnixSignalHandler()
{
#if defined(AM_POSIX_SIGNALS)
    // Please note: sigaltstack is a per-thread setting only.
    // Setup alternate signal stack (to get backtrace for stack overflow)
    // Canonical size might not be suffcient to get QML backtrace, so we double it
    size_t stackSize = size_t(SIGSTKSZ) * 2 + MINSIGSTKSZ;
    stack_t sigstack;
    // ASAN and valgrind would report malloc() as a leak. In addition, we avoid the
    // signal stack being close to a possibly corrupted heap this way.
    sigstack.ss_sp = mmap(nullptr, stackSize, PROT_READ | PROT_WRITE, MAP_PRIVATE | MAP_ANON, -1, 0);
    if (sigstack.ss_sp != MAP_FAILED) {
        sigstack.ss_size = stackSize;
        sigstack.ss_flags = 0;
        sigaltstack(&sigstack, nullptr);
    } else {
        // this code runs before all other static constructors
        qWarning("WARNING: UnixSignalHandler failed to allocate memory for an alternate signal stack.");
    }
#endif
}

UnixSignalHandler *UnixSignalHandler::instance()
{
    if (Q_UNLIKELY(!s_instance))
        s_instance = new UnixSignalHandler();
    return s_instance;
}

const char *UnixSignalHandler::signalName(int sig)
{
#if defined(Q_OS_UNIX)
#  if  defined(__GLIBC__) && (__GLIBC__ >= 2) && (__GLIBC_MINOR__ >= 32)
    return sigdescr_np(sig);
#  else
    return strsignal(sig); // not async-signal-safe
#  endif
#else
    Q_UNUSED(sig)
    return "<unknown>";
#endif
}

void UnixSignalHandler::resetToDefault(int sig)
{
    auto sigs = { sig };
    resetToDefault(sigs);
}

void UnixSignalHandler::resetToDefault(std::initializer_list<int> sigs)
{
    for (int sig : sigs) {
        m_resetSignalMask |= am_sigmask(sig);
        signal(sig, SIG_DFL);
    }
}

std::vector<int> UnixSignalHandler::reinstallIfNeeded(std::initializer_list<int> sigs)
{
    // Make sure our handler is still active and not blocked
    // Returns the list of signals that had to be reinstalled

    std::vector<int> result;
    QVector<int> reinstallSigs { sigs };

#if defined(AM_POSIX_SIGNALS)
    struct sigaction sigact;
    sigset_t unblockSet;
    sigemptyset(&unblockSet);
#endif

    // This is UB! We cannot guarantee that the signal handler is not currently executing and
    // iterating over this list. In practice, this is a none-issue in the AM however, because this
    // reinstall() call should only happen once during startup.
    // To do it right, we would need a lock-free list structure for m_handlers.

    for (const auto &h : std::as_const(m_handlers)) {
        int sig = h.m_signal;
        if (!h.m_disabled && reinstallSigs.contains(sig)) {
#if defined(AM_POSIX_SIGNALS)
            sigaddset(&unblockSet, sig);

            if ((sigaction(sig, nullptr, &sigact) < 0) || (sigact.sa_handler != &signalHandler)) {
                sigact.sa_flags = SA_ONSTACK;
                sigact.sa_handler = &signalHandler;
                sigemptyset(&sigact.sa_mask);
                sigaction(sig, &sigact, nullptr);
                result.push_back(sig);
            }
#else
            if (signal(sig, &signalHandler) != &signalHandler)
                result.push_back(sig);
#endif
        }
    }

#if defined(AM_POSIX_SIGNALS)
    sigprocmask(SIG_UNBLOCK, &unblockSet, nullptr);
#endif
    return result;
}

bool UnixSignalHandler::install(Type handlerType, int sig, const std::function<void (int)> &handler)
{
    auto sigs = { sig };
    return install(handlerType, sigs, handler);
}

void UnixSignalHandler::signalHandler(int sig)
{
    // this lambda is the low-level signal handler multiplexer
    auto that = UnixSignalHandler::instance();
    that->m_currentSignal = sig;

    for (const auto &h : std::as_const(that->m_handlers)) {
        if ((h.m_signal == sig) && !h.m_disabled) {
            if (!h.m_qt) {
                h.m_handler(sig);
            } else {
#if defined(Q_OS_UNIX)
                auto dummy = write(that->m_pipe[1], &sig, sizeof(int));
                Q_UNUSED(dummy)
#elif defined(Q_OS_WIN)
                // we're running in a separate thread now
                that->m_winLock.lock();
                that->m_signalsForEventLoop << sig;
                that->m_winLock.unlock();
                PulseEvent(that->m_winEvent->handle());
#endif
            }
        }
    }
    if (that->m_resetSignalMask) {
        // Someone called resetToDefault - now's a good time to handle it.
        // We can not remove the entries in the list, because that would (a) allocate and (b)
        // step on code that might be iterating over the list in the "Forwarded" handler.

        for (const auto &h : std::as_const(that->m_handlers)) {
            if (that->m_resetSignalMask & am_sigmask(h.m_signal))
                h.m_disabled = true;
        }
        that->m_resetSignalMask = 0;
    }
    that->m_currentSignal = 0;
};


bool UnixSignalHandler::install(Type handlerType, std::initializer_list<int> sigs,
                                const std::function<void(int)> &handler)
{
    if (m_currentSignal) {
        // installing a signal handler from within a signal handler shouldn't be necessary
        return false;
    }

    if (handlerType == ForwardedToEventLoopHandler) {
#if defined(Q_OS_UNIX)
        if ((m_pipe[0] == -1) && qApp) {
            auto dummy = pipe(m_pipe);
            Q_UNUSED(dummy)

            auto sn = new QSocketNotifier(m_pipe[0], QSocketNotifier::Read, this);
            connect(sn, &QSocketNotifier::activated, qApp, [this]() {
                // this lambda is the "signal handler" multiplexer within the Qt event loop
                int sig = 0;

                if (read(m_pipe[0], &sig, sizeof(int)) != sizeof(int)) {
                    qCWarning(LogSystem) << "Error reading from signal handler:" << strerror(errno);
                    return;
                }

                for (const auto &h : std::as_const(m_handlers)) {
                    if (h.m_qt && (h.m_signal == sig) && !h.m_disabled)
                        h.m_handler(sig);
                }
            });
        }
#elif defined(Q_OS_WIN)
        if (!m_winEvent) {
            m_winEvent = new QWinEventNotifier(CreateEventW(nullptr, false, false, nullptr), this);

            connect(m_winEvent, &QWinEventNotifier::activated, qApp, [this]() {
                // this lambda is the "signal handler" multiplexer within the Qt event loop
                m_winLock.lock();
                for (const int &sig : std::as_const(m_signalsForEventLoop)) {
                    for (const auto &h : std::as_const(m_handlers)) {
                        if (h.m_qt && (h.m_signal == sig) && !h.m_disabled)
                            h.m_handler(sig);
                    }
                }
                m_signalsForEventLoop.clear();
                m_winLock.unlock();
            });
        }
#else
        qCWarning(LogSystem) << "Unix signal handling via 'ForwardedToEventLoopHandler' is not "
                                "supported on this platform";
        return false;
#endif
    }

    // This is UB! We cannot guarantee that the signal handler is not currently executing and
    // iterating over this list. In practice, this is a none-issue in the AM however, because all
    // install() calls are done right at startup time.
    // To do it right, we would need a lock-free list structure for m_handlers.
    for (int sig : sigs)
        m_handlers.emplace_back(sig, handlerType == ForwardedToEventLoopHandler, handler);

#if defined(AM_POSIX_SIGNALS)
    struct sigaction sigact;
    sigact.sa_flags = SA_ONSTACK;
    sigact.sa_handler = &signalHandler;

    sigemptyset(&sigact.sa_mask);
    sigset_t unblockSet;
    sigemptyset(&unblockSet);

    for (int sig : sigs) {
        sigaddset(&unblockSet, sig);
        sigaction(sig, &sigact, nullptr);
        m_resetSignalMask &= ~am_sigmask(sig); // cancel unfinished reset
    }
    sigprocmask(SIG_UNBLOCK, &unblockSet, nullptr);
#else
    for (int sig : sigs)
        signal(sig, &signalHandler);
#endif
    return true;
}

UnixSignalHandler::SigHandler::SigHandler(int signal, bool qt, const std::function<void (int)> &handler)
    : m_signal(signal), m_qt(qt), m_handler(handler)
{ }


QT_END_NAMESPACE_AM

#include "moc_unixsignalhandler.cpp"