1//===-- MainLoop.cpp --------------------------------------------*- C++ -*-===//
2//
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
6//
7//===----------------------------------------------------------------------===//
8
9#include "llvm/Config/llvm-config.h"
10#include "lldb/Host/Config.h"
11
12#include "lldb/Host/MainLoop.h"
13#include "lldb/Host/PosixApi.h"
14#include "lldb/Utility/Status.h"
15#include <algorithm>
16#include <cassert>
17#include <cerrno>
18#include <csignal>
19#include <time.h>
20#include <vector>
21
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).
26
27#if HAVE_SYS_EVENT_H
28#include <sys/event.h>
29#elif defined(_WIN32)
30#include <winsock2.h>
31#elif defined(__ANDROID__)
32#include <sys/syscall.h>
33#else
34#include <poll.h>
35#endif
36
37#ifdef _WIN32
38#define POLL WSAPoll
39#else
40#define POLL poll
41#endif
42
43#if SIGNAL_POLLING_UNSUPPORTED
44#ifdef _WIN32
45typedef int sigset_t;
46typedef int siginfo_t;
47#endif
48
49int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout_ts,
50          const sigset_t *) {
51  int timeout =
52      (timeout_ts == nullptr)
53          ? -1
54          : (timeout_ts->tv_sec * 1000 + timeout_ts->tv_nsec / 1000000);
55  return POLL(fds, nfds, timeout);
56}
57
58#endif
59
60using namespace lldb;
61using namespace lldb_private;
62
63static sig_atomic_t g_signal_flags[NSIG];
64
65#ifndef SIGNAL_POLLING_UNSUPPORTED
66static void SignalHandler(int signo, siginfo_t *info, void *) {
67  assert(signo < NSIG);
68  g_signal_flags[signo] = 1;
69}
70#endif
71
72class MainLoop::RunImpl {
73public:
74  RunImpl(MainLoop &loop);
75  ~RunImpl() = default;
76
77  Status Poll();
78  void ProcessEvents();
79
80private:
81  MainLoop &loop;
82
83#if HAVE_SYS_EVENT_H
84  std::vector<struct kevent> in_events;
85  struct kevent out_events[4];
86  int num_events = -1;
87
88#else
89#ifdef __ANDROID__
90  fd_set read_fd_set;
91#else
92  std::vector<struct pollfd> read_fds;
93#endif
94
95  sigset_t get_sigmask();
96#endif
97};
98
99#if HAVE_SYS_EVENT_H
100MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
101  in_events.reserve(loop.m_read_fds.size());
102}
103
104Status MainLoop::RunImpl::Poll() {
105  in_events.resize(loop.m_read_fds.size());
106  unsigned i = 0;
107  for (auto &fd : loop.m_read_fds)
108    EV_SET(&in_events[i++], fd.first, EVFILT_READ, EV_ADD, 0, 0, 0);
109
110  num_events = kevent(loop.m_kqueue, in_events.data(), in_events.size(),
111                      out_events, llvm::array_lengthof(out_events), nullptr);
112
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
117      num_events = 0;
118    } else
119      return Status(errno, eErrorTypePOSIX);
120  }
121  return Status();
122}
123
124void MainLoop::RunImpl::ProcessEvents() {
125  assert(num_events >= 0);
126  for (int i = 0; i < num_events; ++i) {
127    if (loop.m_terminate_request)
128      return;
129    switch (out_events[i].filter) {
130    case EVFILT_READ:
131      loop.ProcessReadObject(out_events[i].ident);
132      break;
133    case EVFILT_SIGNAL:
134      loop.ProcessSignal(out_events[i].ident);
135      break;
136    default:
137      llvm_unreachable("Unknown event");
138    }
139  }
140}
141#else
142MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
143#ifndef __ANDROID__
144  read_fds.reserve(loop.m_read_fds.size());
145#endif
146}
147
148sigset_t MainLoop::RunImpl::get_sigmask() {
149  sigset_t sigmask;
150#if defined(_WIN32)
151  sigmask = 0;
152#elif SIGNAL_POLLING_UNSUPPORTED
153  sigemptyset(&sigmask);
154#else
155  int ret = pthread_sigmask(SIG_SETMASK, nullptr, &sigmask);
156  assert(ret == 0);
157  (void) ret;
158
159  for (const auto &sig : loop.m_signals)
160    sigdelset(&sigmask, sig.first);
161#endif
162  return sigmask;
163}
164
165#ifdef __ANDROID__
166Status 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.
172
173  FD_ZERO(&read_fd_set);
174  int nfds = 0;
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);
178  }
179
180  union {
181    sigset_t set;
182    uint64_t pad;
183  } kernel_sigset;
184  memset(&kernel_sigset, 0, sizeof(kernel_sigset));
185  kernel_sigset.set = get_sigmask();
186
187  struct {
188    void *sigset_ptr;
189    size_t sigset_len;
190  } extra_data = {&kernel_sigset, sizeof(kernel_sigset)};
191  if (syscall(__NR_pselect6, nfds, &read_fd_set, nullptr, nullptr, nullptr,
192              &extra_data) == -1 &&
193      errno != EINTR)
194    return Status(errno, eErrorTypePOSIX);
195
196  return Status();
197}
198#else
199Status MainLoop::RunImpl::Poll() {
200  read_fds.clear();
201
202  sigset_t sigmask = get_sigmask();
203
204  for (const auto &fd : loop.m_read_fds) {
205    struct pollfd pfd;
206    pfd.fd = fd.first;
207    pfd.events = POLLIN;
208    pfd.revents = 0;
209    read_fds.push_back(pfd);
210  }
211
212  if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 &&
213      errno != EINTR)
214    return Status(errno, eErrorTypePOSIX);
215
216  return Status();
217}
218#endif
219
220void MainLoop::RunImpl::ProcessEvents() {
221#ifdef __ANDROID__
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);
230
231  for (const auto &handle : fds) {
232#else
233  for (const auto &fd : read_fds) {
234    if ((fd.revents & (POLLIN | POLLHUP)) == 0)
235      continue;
236    IOObject::WaitableHandle handle = fd.fd;
237#endif
238    if (loop.m_terminate_request)
239      return;
240
241    loop.ProcessReadObject(handle);
242  }
243
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);
248
249  for (const auto &signal : signals) {
250    if (loop.m_terminate_request)
251      return;
252    g_signal_flags[signal] = 0;
253    loop.ProcessSignal(signal);
254  }
255}
256#endif
257
258MainLoop::MainLoop() {
259#if HAVE_SYS_EVENT_H
260  m_kqueue = kqueue();
261  assert(m_kqueue >= 0);
262#endif
263}
264MainLoop::~MainLoop() {
265#if HAVE_SYS_EVENT_H
266  close(m_kqueue);
267#endif
268  assert(m_read_fds.size() == 0);
269  assert(m_signals.size() == 0);
270}
271
272MainLoop::ReadHandleUP MainLoop::RegisterReadObject(const IOObjectSP &object_sp,
273                                                    const Callback &callback,
274                                                    Status &error) {
275#ifdef _WIN32
276  if (object_sp->GetFdType() != IOObject:: eFDTypeSocket) {
277    error.SetErrorString("MainLoop: non-socket types unsupported on Windows");
278    return nullptr;
279  }
280#endif
281  if (!object_sp || !object_sp->IsValid()) {
282    error.SetErrorString("IO object is not valid.");
283    return nullptr;
284  }
285
286  const bool inserted =
287      m_read_fds.insert({object_sp->GetWaitableHandle(), callback}).second;
288  if (!inserted) {
289    error.SetErrorStringWithFormat("File descriptor %d already monitored.",
290                                   object_sp->GetWaitableHandle());
291    return nullptr;
292  }
293
294  return CreateReadHandle(object_sp);
295}
296
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.
299MainLoop::SignalHandleUP
300MainLoop::RegisterSignal(int signo, const Callback &callback, Status &error) {
301#ifdef SIGNAL_POLLING_UNSUPPORTED
302  error.SetErrorString("Signal polling is not supported on this platform.");
303  return nullptr;
304#else
305  if (m_signals.find(signo) != m_signals.end()) {
306    error.SetErrorStringWithFormat("Signal %d already monitored.", signo);
307    return nullptr;
308  }
309
310  SignalInfo info;
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);
317  sigset_t old_set;
318
319  g_signal_flags[signo] = 0;
320
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);
324  (void)ret;
325  assert(ret == 0 && "sigaction failed");
326
327#if HAVE_SYS_EVENT_H
328  struct kevent ev;
329  EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0);
330  ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
331  assert(ret == 0);
332#endif
333
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});
342
343  return SignalHandleUP(new SignalHandle(*this, signo));
344#endif
345}
346
347void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) {
348  bool erased = m_read_fds.erase(handle);
349  UNUSED_IF_ASSERT_DISABLED(erased);
350  assert(erased);
351}
352
353void MainLoop::UnregisterSignal(int signo) {
354#if SIGNAL_POLLING_UNSUPPORTED
355  Status("Signal polling is not supported on this platform.");
356#else
357  auto it = m_signals.find(signo);
358  assert(it != m_signals.end());
359
360  sigaction(signo, &it->second.old_action, nullptr);
361
362  sigset_t set;
363  sigemptyset(&set);
364  sigaddset(&set, signo);
365  int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK,
366                            &set, nullptr);
367  assert(ret == 0);
368  (void)ret;
369
370#if HAVE_SYS_EVENT_H
371  struct kevent ev;
372  EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0);
373  ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
374  assert(ret == 0);
375#endif
376
377  m_signals.erase(it);
378#endif
379}
380
381Status MainLoop::Run() {
382  m_terminate_request = false;
383
384  Status error;
385  RunImpl impl(*this);
386
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())) {
389
390    error = impl.Poll();
391    if (error.Fail())
392      return error;
393
394    impl.ProcessEvents();
395  }
396  return Status();
397}
398
399void 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
403}
404
405void 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
409}
410