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"
11 #include "lldb/Host/MainLoop.h"
12 #include "lldb/Host/PosixApi.h"
13 #include "lldb/Utility/Status.h"
21 // Multiplexing is implemented using kqueue on systems that support it (BSD
22 // variants including OSX). On linux we use ppoll, while android uses pselect
23 // (ppoll is present but not implemented properly). On windows we use WSApoll
24 // (which does not support signals).
27 #include <sys/event.h>
30 #elif defined(__ANDROID__)
31 #include <sys/syscall.h>
42 #if SIGNAL_POLLING_UNSUPPORTED
45 typedef int siginfo_t;
48 int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout_ts,
51 (timeout_ts == nullptr)
53 : (timeout_ts->tv_sec * 1000 + timeout_ts->tv_nsec / 1000000);
54 return POLL(fds, nfds, timeout);
60 using namespace lldb_private;
62 static sig_atomic_t g_signal_flags[NSIG];
64 #ifndef SIGNAL_POLLING_UNSUPPORTED
65 static void SignalHandler(int signo, siginfo_t *info, void *) {
67 g_signal_flags[signo] = 1;
71 class MainLoop::RunImpl {
73 RunImpl(MainLoop &loop);
83 std::vector<struct kevent> in_events;
84 struct kevent out_events[4];
91 std::vector<struct pollfd> read_fds;
94 sigset_t get_sigmask();
99 MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
100 in_events.reserve(loop.m_read_fds.size());
103 Status MainLoop::RunImpl::Poll() {
104 in_events.resize(loop.m_read_fds.size());
106 for (auto &fd : loop.m_read_fds)
107 EV_SET(&in_events[i++], fd.first, EVFILT_READ, EV_ADD, 0, 0, 0);
109 num_events = kevent(loop.m_kqueue, in_events.data(), in_events.size(),
110 out_events, llvm::array_lengthof(out_events), nullptr);
112 if (num_events < 0) {
113 if (errno == EINTR) {
114 // in case of EINTR, let the main loop run one iteration
115 // we need to zero num_events to avoid assertions failing
118 return Status(errno, eErrorTypePOSIX);
123 void MainLoop::RunImpl::ProcessEvents() {
124 assert(num_events >= 0);
125 for (int i = 0; i < num_events; ++i) {
126 if (loop.m_terminate_request)
128 switch (out_events[i].filter) {
130 loop.ProcessReadObject(out_events[i].ident);
133 loop.ProcessSignal(out_events[i].ident);
136 llvm_unreachable("Unknown event");
141 MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
143 read_fds.reserve(loop.m_read_fds.size());
147 sigset_t MainLoop::RunImpl::get_sigmask() {
151 #elif SIGNAL_POLLING_UNSUPPORTED
152 sigemptyset(&sigmask);
154 int ret = pthread_sigmask(SIG_SETMASK, nullptr, &sigmask);
158 for (const auto &sig : loop.m_signals)
159 sigdelset(&sigmask, sig.first);
165 Status MainLoop::RunImpl::Poll() {
166 // ppoll(2) is not supported on older all android versions. Also, older
167 // versions android (API <= 19) implemented pselect in a non-atomic way, as a
168 // combination of pthread_sigmask and select. This is not sufficient for us,
169 // as we rely on the atomicity to correctly implement signal polling, so we
170 // call the underlying syscall ourselves.
172 FD_ZERO(&read_fd_set);
174 for (const auto &fd : loop.m_read_fds) {
175 FD_SET(fd.first, &read_fd_set);
176 nfds = std::max(nfds, fd.first + 1);
183 memset(&kernel_sigset, 0, sizeof(kernel_sigset));
184 kernel_sigset.set = get_sigmask();
189 } extra_data = {&kernel_sigset, sizeof(kernel_sigset)};
190 if (syscall(__NR_pselect6, nfds, &read_fd_set, nullptr, nullptr, nullptr,
191 &extra_data) == -1 &&
193 return Status(errno, eErrorTypePOSIX);
198 Status MainLoop::RunImpl::Poll() {
201 sigset_t sigmask = get_sigmask();
203 for (const auto &fd : loop.m_read_fds) {
208 read_fds.push_back(pfd);
211 if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 &&
213 return Status(errno, eErrorTypePOSIX);
219 void MainLoop::RunImpl::ProcessEvents() {
221 // Collect first all readable file descriptors into a separate vector and
222 // then iterate over it to invoke callbacks. Iterating directly over
223 // loop.m_read_fds is not possible because the callbacks can modify the
224 // container which could invalidate the iterator.
225 std::vector<IOObject::WaitableHandle> fds;
226 for (const auto &fd : loop.m_read_fds)
227 if (FD_ISSET(fd.first, &read_fd_set))
228 fds.push_back(fd.first);
230 for (const auto &handle : fds) {
232 for (const auto &fd : read_fds) {
233 if ((fd.revents & (POLLIN | POLLHUP)) == 0)
235 IOObject::WaitableHandle handle = fd.fd;
237 if (loop.m_terminate_request)
240 loop.ProcessReadObject(handle);
243 std::vector<int> signals;
244 for (const auto &entry : loop.m_signals)
245 if (g_signal_flags[entry.first] != 0)
246 signals.push_back(entry.first);
248 for (const auto &signal : signals) {
249 if (loop.m_terminate_request)
251 g_signal_flags[signal] = 0;
252 loop.ProcessSignal(signal);
257 MainLoop::MainLoop() {
260 assert(m_kqueue >= 0);
263 MainLoop::~MainLoop() {
267 assert(m_read_fds.size() == 0);
268 assert(m_signals.size() == 0);
271 MainLoop::ReadHandleUP MainLoop::RegisterReadObject(const IOObjectSP &object_sp,
272 const Callback &callback,
275 if (object_sp->GetFdType() != IOObject:: eFDTypeSocket) {
276 error.SetErrorString("MainLoop: non-socket types unsupported on Windows");
280 if (!object_sp || !object_sp->IsValid()) {
281 error.SetErrorString("IO object is not valid.");
285 const bool inserted =
286 m_read_fds.insert({object_sp->GetWaitableHandle(), callback}).second;
288 error.SetErrorStringWithFormat("File descriptor %d already monitored.",
289 object_sp->GetWaitableHandle());
293 return CreateReadHandle(object_sp);
296 // We shall block the signal, then install the signal handler. The signal will
297 // be unblocked in the Run() function to check for signal delivery.
298 MainLoop::SignalHandleUP
299 MainLoop::RegisterSignal(int signo, const Callback &callback, Status &error) {
300 #ifdef SIGNAL_POLLING_UNSUPPORTED
301 error.SetErrorString("Signal polling is not supported on this platform.");
304 if (m_signals.find(signo) != m_signals.end()) {
305 error.SetErrorStringWithFormat("Signal %d already monitored.", signo);
310 info.callback = callback;
311 struct sigaction new_action;
312 new_action.sa_sigaction = &SignalHandler;
313 new_action.sa_flags = SA_SIGINFO;
314 sigemptyset(&new_action.sa_mask);
315 sigaddset(&new_action.sa_mask, signo);
318 g_signal_flags[signo] = 0;
320 // Even if using kqueue, the signal handler will still be invoked, so it's
321 // important to replace it with our "benign" handler.
322 int ret = sigaction(signo, &new_action, &info.old_action);
323 assert(ret == 0 && "sigaction failed");
327 EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0);
328 ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
332 // If we're using kqueue, the signal needs to be unblocked in order to
333 // receive it. If using pselect/ppoll, we need to block it, and later unblock
334 // it as a part of the system call.
335 ret = pthread_sigmask(HAVE_SYS_EVENT_H ? SIG_UNBLOCK : SIG_BLOCK,
336 &new_action.sa_mask, &old_set);
337 assert(ret == 0 && "pthread_sigmask failed");
338 info.was_blocked = sigismember(&old_set, signo);
339 m_signals.insert({signo, info});
341 return SignalHandleUP(new SignalHandle(*this, signo));
345 void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) {
346 bool erased = m_read_fds.erase(handle);
347 UNUSED_IF_ASSERT_DISABLED(erased);
351 void MainLoop::UnregisterSignal(int signo) {
352 #if SIGNAL_POLLING_UNSUPPORTED
353 Status("Signal polling is not supported on this platform.");
355 auto it = m_signals.find(signo);
356 assert(it != m_signals.end());
358 sigaction(signo, &it->second.old_action, nullptr);
362 sigaddset(&set, signo);
363 int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK,
370 EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0);
371 ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
379 Status MainLoop::Run() {
380 m_terminate_request = false;
385 // run until termination or until we run out of things to listen to
386 while (!m_terminate_request && (!m_read_fds.empty() || !m_signals.empty())) {
392 impl.ProcessEvents();
397 void MainLoop::ProcessSignal(int signo) {
398 auto it = m_signals.find(signo);
399 if (it != m_signals.end())
400 it->second.callback(*this); // Do the work
403 void MainLoop::ProcessReadObject(IOObject::WaitableHandle handle) {
404 auto it = m_read_fds.find(handle);
405 if (it != m_read_fds.end())
406 it->second(*this); // Do the work