1 //===-- MainLoop.cpp --------------------------------------------*- C++ -*-===//
3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4 // See https://llvm.org/LICENSE.txt for license information.
5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
7 //===----------------------------------------------------------------------===//
9 #include "llvm/Config/llvm-config.h"
10 #include "lldb/Host/Config.h"
12 #include "lldb/Host/MainLoop.h"
13 #include "lldb/Host/PosixApi.h"
14 #include "lldb/Utility/Status.h"
22 // Multiplexing is implemented using kqueue on systems that support it (BSD
23 // variants including OSX). On linux we use ppoll, while android uses pselect
24 // (ppoll is present but not implemented properly). On windows we use WSApoll
25 // (which does not support signals).
28 #include <sys/event.h>
31 #elif defined(__ANDROID__)
32 #include <sys/syscall.h>
43 #if SIGNAL_POLLING_UNSUPPORTED
46 typedef int siginfo_t;
49 int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout_ts,
52 (timeout_ts == nullptr)
54 : (timeout_ts->tv_sec * 1000 + timeout_ts->tv_nsec / 1000000);
55 return POLL(fds, nfds, timeout);
61 using namespace lldb_private;
63 static sig_atomic_t g_signal_flags[NSIG];
65 #ifndef SIGNAL_POLLING_UNSUPPORTED
66 static void SignalHandler(int signo, siginfo_t *info, void *) {
68 g_signal_flags[signo] = 1;
72 class MainLoop::RunImpl {
74 RunImpl(MainLoop &loop);
84 std::vector<struct kevent> in_events;
85 struct kevent out_events[4];
92 std::vector<struct pollfd> read_fds;
95 sigset_t get_sigmask();
100 MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
101 in_events.reserve(loop.m_read_fds.size());
104 Status MainLoop::RunImpl::Poll() {
105 in_events.resize(loop.m_read_fds.size());
107 for (auto &fd : loop.m_read_fds)
108 EV_SET(&in_events[i++], fd.first, EVFILT_READ, EV_ADD, 0, 0, 0);
110 num_events = kevent(loop.m_kqueue, in_events.data(), in_events.size(),
111 out_events, llvm::array_lengthof(out_events), nullptr);
113 if (num_events < 0) {
114 if (errno == EINTR) {
115 // in case of EINTR, let the main loop run one iteration
116 // we need to zero num_events to avoid assertions failing
119 return Status(errno, eErrorTypePOSIX);
124 void MainLoop::RunImpl::ProcessEvents() {
125 assert(num_events >= 0);
126 for (int i = 0; i < num_events; ++i) {
127 if (loop.m_terminate_request)
129 switch (out_events[i].filter) {
131 loop.ProcessReadObject(out_events[i].ident);
134 loop.ProcessSignal(out_events[i].ident);
137 llvm_unreachable("Unknown event");
142 MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
144 read_fds.reserve(loop.m_read_fds.size());
148 sigset_t MainLoop::RunImpl::get_sigmask() {
152 #elif SIGNAL_POLLING_UNSUPPORTED
153 sigemptyset(&sigmask);
155 int ret = pthread_sigmask(SIG_SETMASK, nullptr, &sigmask);
159 for (const auto &sig : loop.m_signals)
160 sigdelset(&sigmask, sig.first);
166 Status MainLoop::RunImpl::Poll() {
167 // ppoll(2) is not supported on older all android versions. Also, older
168 // versions android (API <= 19) implemented pselect in a non-atomic way, as a
169 // combination of pthread_sigmask and select. This is not sufficient for us,
170 // as we rely on the atomicity to correctly implement signal polling, so we
171 // call the underlying syscall ourselves.
173 FD_ZERO(&read_fd_set);
175 for (const auto &fd : loop.m_read_fds) {
176 FD_SET(fd.first, &read_fd_set);
177 nfds = std::max(nfds, fd.first + 1);
184 memset(&kernel_sigset, 0, sizeof(kernel_sigset));
185 kernel_sigset.set = get_sigmask();
190 } extra_data = {&kernel_sigset, sizeof(kernel_sigset)};
191 if (syscall(__NR_pselect6, nfds, &read_fd_set, nullptr, nullptr, nullptr,
192 &extra_data) == -1 &&
194 return Status(errno, eErrorTypePOSIX);
199 Status MainLoop::RunImpl::Poll() {
202 sigset_t sigmask = get_sigmask();
204 for (const auto &fd : loop.m_read_fds) {
209 read_fds.push_back(pfd);
212 if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 &&
214 return Status(errno, eErrorTypePOSIX);
220 void MainLoop::RunImpl::ProcessEvents() {
222 // Collect first all readable file descriptors into a separate vector and
223 // then iterate over it to invoke callbacks. Iterating directly over
224 // loop.m_read_fds is not possible because the callbacks can modify the
225 // container which could invalidate the iterator.
226 std::vector<IOObject::WaitableHandle> fds;
227 for (const auto &fd : loop.m_read_fds)
228 if (FD_ISSET(fd.first, &read_fd_set))
229 fds.push_back(fd.first);
231 for (const auto &handle : fds) {
233 for (const auto &fd : read_fds) {
234 if ((fd.revents & (POLLIN | POLLHUP)) == 0)
236 IOObject::WaitableHandle handle = fd.fd;
238 if (loop.m_terminate_request)
241 loop.ProcessReadObject(handle);
244 std::vector<int> signals;
245 for (const auto &entry : loop.m_signals)
246 if (g_signal_flags[entry.first] != 0)
247 signals.push_back(entry.first);
249 for (const auto &signal : signals) {
250 if (loop.m_terminate_request)
252 g_signal_flags[signal] = 0;
253 loop.ProcessSignal(signal);
258 MainLoop::MainLoop() {
261 assert(m_kqueue >= 0);
264 MainLoop::~MainLoop() {
268 assert(m_read_fds.size() == 0);
269 assert(m_signals.size() == 0);
272 MainLoop::ReadHandleUP MainLoop::RegisterReadObject(const IOObjectSP &object_sp,
273 const Callback &callback,
276 if (object_sp->GetFdType() != IOObject:: eFDTypeSocket) {
277 error.SetErrorString("MainLoop: non-socket types unsupported on Windows");
281 if (!object_sp || !object_sp->IsValid()) {
282 error.SetErrorString("IO object is not valid.");
286 const bool inserted =
287 m_read_fds.insert({object_sp->GetWaitableHandle(), callback}).second;
289 error.SetErrorStringWithFormat("File descriptor %d already monitored.",
290 object_sp->GetWaitableHandle());
294 return CreateReadHandle(object_sp);
297 // We shall block the signal, then install the signal handler. The signal will
298 // be unblocked in the Run() function to check for signal delivery.
299 MainLoop::SignalHandleUP
300 MainLoop::RegisterSignal(int signo, const Callback &callback, Status &error) {
301 #ifdef SIGNAL_POLLING_UNSUPPORTED
302 error.SetErrorString("Signal polling is not supported on this platform.");
305 if (m_signals.find(signo) != m_signals.end()) {
306 error.SetErrorStringWithFormat("Signal %d already monitored.", signo);
311 info.callback = callback;
312 struct sigaction new_action;
313 new_action.sa_sigaction = &SignalHandler;
314 new_action.sa_flags = SA_SIGINFO;
315 sigemptyset(&new_action.sa_mask);
316 sigaddset(&new_action.sa_mask, signo);
319 g_signal_flags[signo] = 0;
321 // Even if using kqueue, the signal handler will still be invoked, so it's
322 // important to replace it with our "benign" handler.
323 int ret = sigaction(signo, &new_action, &info.old_action);
325 assert(ret == 0 && "sigaction failed");
329 EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0);
330 ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
334 // If we're using kqueue, the signal needs to be unblocked in order to
335 // receive it. If using pselect/ppoll, we need to block it, and later unblock
336 // it as a part of the system call.
337 ret = pthread_sigmask(HAVE_SYS_EVENT_H ? SIG_UNBLOCK : SIG_BLOCK,
338 &new_action.sa_mask, &old_set);
339 assert(ret == 0 && "pthread_sigmask failed");
340 info.was_blocked = sigismember(&old_set, signo);
341 m_signals.insert({signo, info});
343 return SignalHandleUP(new SignalHandle(*this, signo));
347 void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) {
348 bool erased = m_read_fds.erase(handle);
349 UNUSED_IF_ASSERT_DISABLED(erased);
353 void MainLoop::UnregisterSignal(int signo) {
354 #if SIGNAL_POLLING_UNSUPPORTED
355 Status("Signal polling is not supported on this platform.");
357 auto it = m_signals.find(signo);
358 assert(it != m_signals.end());
360 sigaction(signo, &it->second.old_action, nullptr);
364 sigaddset(&set, signo);
365 int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK,
372 EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0);
373 ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
381 Status MainLoop::Run() {
382 m_terminate_request = false;
387 // run until termination or until we run out of things to listen to
388 while (!m_terminate_request && (!m_read_fds.empty() || !m_signals.empty())) {
394 impl.ProcessEvents();
399 void MainLoop::ProcessSignal(int signo) {
400 auto it = m_signals.find(signo);
401 if (it != m_signals.end())
402 it->second.callback(*this); // Do the work
405 void MainLoop::ProcessReadObject(IOObject::WaitableHandle handle) {
406 auto it = m_read_fds.find(handle);
407 if (it != m_read_fds.end())
408 it->second(*this); // Do the work