summaryrefslogtreecommitdiff
path: root/src/common-lib/unixsignalhandler.cpp
blob: 0602d6c6092a506945143703f12a34e1f81967b1 (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
// 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 <errno.h>

#if defined(Q_OS_WIN)
#  include <windows.h>
#  include <synchapi.h>
#else
#  include <sys/mman.h>
#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(Q_OS_UNIX) && !defined(Q_OS_QNX)
    // 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 = SIGSTKSZ * 2;
    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  __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(const std::initializer_list<int> &sigs)
{
    for (int sig : sigs) {
        m_resetSignalMask |= am_sigmask(sig);
        signal(sig, SIG_DFL);
    }
}

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

bool UnixSignalHandler::install(Type handlerType, const std::initializer_list<int> &sigs,
                                const std::function<void(int)> &handler)
{
    auto sigHandler = [](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;
    };

    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(Q_OS_UNIX) && !defined(Q_OS_QNX)
    struct sigaction sigact;
    sigact.sa_flags = SA_ONSTACK;
    sigact.sa_handler = sigHandler;

    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, sigHandler);
#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"