MainLoop.cpp revision 320970
1//===-- MainLoop.cpp --------------------------------------------*- C++ -*-===//
2//
3//                     The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9
10#include "llvm/Config/llvm-config.h"
11
12#include "lldb/Host/MainLoop.h"
13#include "lldb/Utility/Status.h"
14#include <algorithm>
15#include <cassert>
16#include <cerrno>
17#include <csignal>
18#include <time.h>
19#include <vector>
20
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).
25
26#if HAVE_SYS_EVENT_H
27#include <sys/event.h>
28#elif defined(LLVM_ON_WIN32)
29#include <winsock2.h>
30#else
31#include <poll.h>
32#endif
33
34#ifdef LLVM_ON_WIN32
35#define POLL WSAPoll
36#else
37#define POLL poll
38#endif
39
40#ifdef __ANDROID__
41#define FORCE_PSELECT
42#endif
43
44#if SIGNAL_POLLING_UNSUPPORTED
45#ifdef LLVM_ON_WIN32
46typedef int sigset_t;
47typedef int siginfo_t;
48#endif
49
50int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout_ts,
51          const sigset_t *) {
52  int timeout =
53      (timeout_ts == nullptr)
54          ? -1
55          : (timeout_ts->tv_sec * 1000 + timeout_ts->tv_nsec / 1000000);
56  return POLL(fds, nfds, timeout);
57}
58
59#endif
60
61using namespace lldb;
62using namespace lldb_private;
63
64static sig_atomic_t g_signal_flags[NSIG];
65
66static void SignalHandler(int signo, siginfo_t *info, void *) {
67  assert(signo < NSIG);
68  g_signal_flags[signo] = 1;
69}
70
71class MainLoop::RunImpl {
72public:
73  RunImpl(MainLoop &loop);
74  ~RunImpl() = default;
75
76  Status Poll();
77  void ProcessEvents();
78
79private:
80  MainLoop &loop;
81
82#if HAVE_SYS_EVENT_H
83  std::vector<struct kevent> in_events;
84  struct kevent out_events[4];
85  int num_events = -1;
86
87#else
88#ifdef FORCE_PSELECT
89  fd_set read_fd_set;
90#else
91  std::vector<struct pollfd> read_fds;
92#endif
93
94  sigset_t get_sigmask();
95#endif
96};
97
98#if HAVE_SYS_EVENT_H
99MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
100  in_events.reserve(loop.m_read_fds.size());
101}
102
103Status MainLoop::RunImpl::Poll() {
104  in_events.resize(loop.m_read_fds.size());
105  unsigned i = 0;
106  for (auto &fd : loop.m_read_fds)
107    EV_SET(&in_events[i++], fd.first, EVFILT_READ, EV_ADD, 0, 0, 0);
108
109  num_events = kevent(loop.m_kqueue, in_events.data(), in_events.size(),
110                      out_events, llvm::array_lengthof(out_events), nullptr);
111
112  if (num_events < 0)
113    return Status("kevent() failed with error %d\n", num_events);
114  return Status();
115}
116
117void MainLoop::RunImpl::ProcessEvents() {
118  assert(num_events >= 0);
119  for (int i = 0; i < num_events; ++i) {
120    if (loop.m_terminate_request)
121      return;
122    switch (out_events[i].filter) {
123    case EVFILT_READ:
124      loop.ProcessReadObject(out_events[i].ident);
125      break;
126    case EVFILT_SIGNAL:
127      loop.ProcessSignal(out_events[i].ident);
128      break;
129    default:
130      llvm_unreachable("Unknown event");
131    }
132  }
133}
134#else
135MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
136#ifndef FORCE_PSELECT
137  read_fds.reserve(loop.m_read_fds.size());
138#endif
139}
140
141sigset_t MainLoop::RunImpl::get_sigmask() {
142#if SIGNAL_POLLING_UNSUPPORTED
143  return 0;
144#else
145  sigset_t sigmask;
146  int ret = pthread_sigmask(SIG_SETMASK, nullptr, &sigmask);
147  assert(ret == 0);
148  (void) ret;
149
150  for (const auto &sig : loop.m_signals)
151    sigdelset(&sigmask, sig.first);
152  return sigmask;
153#endif
154}
155
156#ifdef FORCE_PSELECT
157Status MainLoop::RunImpl::Poll() {
158  FD_ZERO(&read_fd_set);
159  int nfds = 0;
160  for (const auto &fd : loop.m_read_fds) {
161    FD_SET(fd.first, &read_fd_set);
162    nfds = std::max(nfds, fd.first + 1);
163  }
164
165  sigset_t sigmask = get_sigmask();
166  if (pselect(nfds, &read_fd_set, nullptr, nullptr, nullptr, &sigmask) == -1 &&
167      errno != EINTR)
168    return Status(errno, eErrorTypePOSIX);
169
170  return Status();
171}
172#else
173Status MainLoop::RunImpl::Poll() {
174  read_fds.clear();
175
176  sigset_t sigmask = get_sigmask();
177
178  for (const auto &fd : loop.m_read_fds) {
179    struct pollfd pfd;
180    pfd.fd = fd.first;
181    pfd.events = POLLIN;
182    pfd.revents = 0;
183    read_fds.push_back(pfd);
184  }
185
186  if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 &&
187      errno != EINTR)
188    return Status(errno, eErrorTypePOSIX);
189
190  return Status();
191}
192#endif
193
194void MainLoop::RunImpl::ProcessEvents() {
195#ifdef FORCE_PSELECT
196  // Collect first all readable file descriptors into a separate vector and then
197  // iterate over it to invoke callbacks. Iterating directly over
198  // loop.m_read_fds is not possible because the callbacks can modify the
199  // container which could invalidate the iterator.
200  std::vector<IOObject::WaitableHandle> fds;
201  for (const auto &fd : loop.m_read_fds)
202    if (FD_ISSET(fd.first, &read_fd_set))
203      fds.push_back(fd.first);
204
205  for (const auto &handle : fds) {
206#else
207  for (const auto &fd : read_fds) {
208    if ((fd.revents & POLLIN) == 0)
209      continue;
210    IOObject::WaitableHandle handle = fd.fd;
211#endif
212    if (loop.m_terminate_request)
213      return;
214
215    loop.ProcessReadObject(handle);
216  }
217
218  std::vector<int> signals;
219  for (const auto &entry : loop.m_signals)
220    if (g_signal_flags[entry.first] != 0)
221      signals.push_back(entry.first);
222
223  for (const auto &signal : signals) {
224    if (loop.m_terminate_request)
225      return;
226    g_signal_flags[signal] = 0;
227    loop.ProcessSignal(signal);
228  }
229}
230#endif
231
232MainLoop::MainLoop() {
233#if HAVE_SYS_EVENT_H
234  m_kqueue = kqueue();
235  assert(m_kqueue >= 0);
236#endif
237}
238MainLoop::~MainLoop() {
239#if HAVE_SYS_EVENT_H
240  close(m_kqueue);
241#endif
242  assert(m_read_fds.size() == 0);
243  assert(m_signals.size() == 0);
244}
245
246MainLoop::ReadHandleUP MainLoop::RegisterReadObject(const IOObjectSP &object_sp,
247                                                    const Callback &callback,
248                                                    Status &error) {
249#ifdef LLVM_ON_WIN32
250  if (object_sp->GetFdType() != IOObject:: eFDTypeSocket) {
251    error.SetErrorString("MainLoop: non-socket types unsupported on Windows");
252    return nullptr;
253  }
254#endif
255  if (!object_sp || !object_sp->IsValid()) {
256    error.SetErrorString("IO object is not valid.");
257    return nullptr;
258  }
259
260  const bool inserted =
261      m_read_fds.insert({object_sp->GetWaitableHandle(), callback}).second;
262  if (!inserted) {
263    error.SetErrorStringWithFormat("File descriptor %d already monitored.",
264                                   object_sp->GetWaitableHandle());
265    return nullptr;
266  }
267
268  return CreateReadHandle(object_sp);
269}
270
271// We shall block the signal, then install the signal handler. The signal will
272// be unblocked in
273// the Run() function to check for signal delivery.
274MainLoop::SignalHandleUP
275MainLoop::RegisterSignal(int signo, const Callback &callback, Status &error) {
276#ifdef SIGNAL_POLLING_UNSUPPORTED
277  error.SetErrorString("Signal polling is not supported on this platform.");
278  return nullptr;
279#else
280  if (m_signals.find(signo) != m_signals.end()) {
281    error.SetErrorStringWithFormat("Signal %d already monitored.", signo);
282    return nullptr;
283  }
284
285  SignalInfo info;
286  info.callback = callback;
287  struct sigaction new_action;
288  new_action.sa_sigaction = &SignalHandler;
289  new_action.sa_flags = SA_SIGINFO;
290  sigemptyset(&new_action.sa_mask);
291  sigaddset(&new_action.sa_mask, signo);
292  sigset_t old_set;
293
294  g_signal_flags[signo] = 0;
295
296  // Even if using kqueue, the signal handler will still be invoked, so it's
297  // important to replace it with our "bening" handler.
298  int ret = sigaction(signo, &new_action, &info.old_action);
299  assert(ret == 0 && "sigaction failed");
300
301#if HAVE_SYS_EVENT_H
302  struct kevent ev;
303  EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0);
304  ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
305  assert(ret == 0);
306#endif
307
308  // If we're using kqueue, the signal needs to be unblocked in order to recieve
309  // it. If using pselect/ppoll, we need to block it, and later unblock it as a
310  // part of the system call.
311  ret = pthread_sigmask(HAVE_SYS_EVENT_H ? SIG_UNBLOCK : SIG_BLOCK,
312                        &new_action.sa_mask, &old_set);
313  assert(ret == 0 && "pthread_sigmask failed");
314  info.was_blocked = sigismember(&old_set, signo);
315  m_signals.insert({signo, info});
316
317  return SignalHandleUP(new SignalHandle(*this, signo));
318#endif
319}
320
321void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) {
322  bool erased = m_read_fds.erase(handle);
323  UNUSED_IF_ASSERT_DISABLED(erased);
324  assert(erased);
325}
326
327void MainLoop::UnregisterSignal(int signo) {
328#if SIGNAL_POLLING_UNSUPPORTED
329  Status("Signal polling is not supported on this platform.");
330#else
331  auto it = m_signals.find(signo);
332  assert(it != m_signals.end());
333
334  sigaction(signo, &it->second.old_action, nullptr);
335
336  sigset_t set;
337  sigemptyset(&set);
338  sigaddset(&set, signo);
339  int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK,
340                            &set, nullptr);
341  assert(ret == 0);
342  (void)ret;
343
344#if HAVE_SYS_EVENT_H
345  struct kevent ev;
346  EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0);
347  ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
348  assert(ret == 0);
349#endif
350
351  m_signals.erase(it);
352#endif
353}
354
355Status MainLoop::Run() {
356  m_terminate_request = false;
357
358  Status error;
359  RunImpl impl(*this);
360
361  // run until termination or until we run out of things to listen to
362  while (!m_terminate_request && (!m_read_fds.empty() || !m_signals.empty())) {
363
364    error = impl.Poll();
365    if (error.Fail())
366      return error;
367
368    impl.ProcessEvents();
369
370    if (m_terminate_request)
371      return Status();
372  }
373  return Status();
374}
375
376void MainLoop::ProcessSignal(int signo) {
377  auto it = m_signals.find(signo);
378  if (it != m_signals.end())
379    it->second.callback(*this); // Do the work
380}
381
382void MainLoop::ProcessReadObject(IOObject::WaitableHandle handle) {
383  auto it = m_read_fds.find(handle);
384  if (it != m_read_fds.end())
385    it->second(*this); // Do the work
386}
387