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/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 #include <sys/syscall.h>
22 
23 // Multiplexing is implemented using kqueue on systems that support it (BSD
24 // variants including OSX). On linux we use ppoll, while android uses pselect
25 // (ppoll is present but not implemented properly). On windows we use WSApoll
26 // (which does not support signals).
27 
28 #if HAVE_SYS_EVENT_H
29 #include <sys/event.h>
30 #elif defined(LLVM_ON_WIN32)
31 #include <winsock2.h>
32 #elif defined(__ANDROID__)
33 #include <sys/syscall.h>
34 #else
35 #include <poll.h>
36 #endif
37 
38 #ifdef LLVM_ON_WIN32
39 #define POLL WSAPoll
40 #else
41 #define POLL poll
42 #endif
43 
44 #if SIGNAL_POLLING_UNSUPPORTED
45 #ifdef LLVM_ON_WIN32
46 typedef int sigset_t;
47 typedef int siginfo_t;
48 #endif
49 
50 int 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 
61 using namespace lldb;
62 using namespace lldb_private;
63 
64 static sig_atomic_t g_signal_flags[NSIG];
65 
66 static void SignalHandler(int signo, siginfo_t *info, void *) {
67   assert(signo < NSIG);
68   g_signal_flags[signo] = 1;
69 }
70 
71 class MainLoop::RunImpl {
72 public:
73   RunImpl(MainLoop &loop);
74   ~RunImpl() = default;
75 
76   Status Poll();
77   void ProcessEvents();
78 
79 private:
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 __ANDROID__
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
99 MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
100   in_events.reserve(loop.m_read_fds.size());
101 }
102 
103 Status 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 
117 void 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
135 MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
136 #ifndef __ANDROID__
137   read_fds.reserve(loop.m_read_fds.size());
138 #endif
139 }
140 
141 sigset_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 __ANDROID__
157 Status MainLoop::RunImpl::Poll() {
158   // ppoll(2) is not supported on older all android versions. Also, older
159   // versions android (API <= 19) implemented pselect in a non-atomic way, as a
160   // combination of pthread_sigmask and select. This is not sufficient for us,
161   // as we rely on the atomicity to correctly implement signal polling, so we
162   // call the underlying syscall ourselves.
163 
164   FD_ZERO(&read_fd_set);
165   int nfds = 0;
166   for (const auto &fd : loop.m_read_fds) {
167     FD_SET(fd.first, &read_fd_set);
168     nfds = std::max(nfds, fd.first + 1);
169   }
170 
171   union {
172     sigset_t set;
173     uint64_t pad;
174   } kernel_sigset;
175   memset(&kernel_sigset, 0, sizeof(kernel_sigset));
176   kernel_sigset.set = get_sigmask();
177 
178   struct {
179     void *sigset_ptr;
180     size_t sigset_len;
181   } extra_data = {&kernel_sigset, sizeof(kernel_sigset)};
182   if (syscall(__NR_pselect6, nfds, &read_fd_set, nullptr, nullptr, nullptr,
183               &extra_data) == -1 &&
184       errno != EINTR)
185     return Status(errno, eErrorTypePOSIX);
186 
187   return Status();
188 }
189 #else
190 Status MainLoop::RunImpl::Poll() {
191   read_fds.clear();
192 
193   sigset_t sigmask = get_sigmask();
194 
195   for (const auto &fd : loop.m_read_fds) {
196     struct pollfd pfd;
197     pfd.fd = fd.first;
198     pfd.events = POLLIN;
199     pfd.revents = 0;
200     read_fds.push_back(pfd);
201   }
202 
203   if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 &&
204       errno != EINTR)
205     return Status(errno, eErrorTypePOSIX);
206 
207   return Status();
208 }
209 #endif
210 
211 void MainLoop::RunImpl::ProcessEvents() {
212 #ifdef __ANDROID__
213   // Collect first all readable file descriptors into a separate vector and then
214   // iterate over it to invoke callbacks. Iterating directly over
215   // loop.m_read_fds is not possible because the callbacks can modify the
216   // container which could invalidate the iterator.
217   std::vector<IOObject::WaitableHandle> fds;
218   for (const auto &fd : loop.m_read_fds)
219     if (FD_ISSET(fd.first, &read_fd_set))
220       fds.push_back(fd.first);
221 
222   for (const auto &handle : fds) {
223 #else
224   for (const auto &fd : read_fds) {
225     if ((fd.revents & POLLIN) == 0)
226       continue;
227     IOObject::WaitableHandle handle = fd.fd;
228 #endif
229     if (loop.m_terminate_request)
230       return;
231 
232     loop.ProcessReadObject(handle);
233   }
234 
235   std::vector<int> signals;
236   for (const auto &entry : loop.m_signals)
237     if (g_signal_flags[entry.first] != 0)
238       signals.push_back(entry.first);
239 
240   for (const auto &signal : signals) {
241     if (loop.m_terminate_request)
242       return;
243     g_signal_flags[signal] = 0;
244     loop.ProcessSignal(signal);
245   }
246 }
247 #endif
248 
249 MainLoop::MainLoop() {
250 #if HAVE_SYS_EVENT_H
251   m_kqueue = kqueue();
252   assert(m_kqueue >= 0);
253 #endif
254 }
255 MainLoop::~MainLoop() {
256 #if HAVE_SYS_EVENT_H
257   close(m_kqueue);
258 #endif
259   assert(m_read_fds.size() == 0);
260   assert(m_signals.size() == 0);
261 }
262 
263 MainLoop::ReadHandleUP MainLoop::RegisterReadObject(const IOObjectSP &object_sp,
264                                                     const Callback &callback,
265                                                     Status &error) {
266 #ifdef LLVM_ON_WIN32
267   if (object_sp->GetFdType() != IOObject:: eFDTypeSocket) {
268     error.SetErrorString("MainLoop: non-socket types unsupported on Windows");
269     return nullptr;
270   }
271 #endif
272   if (!object_sp || !object_sp->IsValid()) {
273     error.SetErrorString("IO object is not valid.");
274     return nullptr;
275   }
276 
277   const bool inserted =
278       m_read_fds.insert({object_sp->GetWaitableHandle(), callback}).second;
279   if (!inserted) {
280     error.SetErrorStringWithFormat("File descriptor %d already monitored.",
281                                    object_sp->GetWaitableHandle());
282     return nullptr;
283   }
284 
285   return CreateReadHandle(object_sp);
286 }
287 
288 // We shall block the signal, then install the signal handler. The signal will
289 // be unblocked in
290 // the Run() function to check for signal delivery.
291 MainLoop::SignalHandleUP
292 MainLoop::RegisterSignal(int signo, const Callback &callback, Status &error) {
293 #ifdef SIGNAL_POLLING_UNSUPPORTED
294   error.SetErrorString("Signal polling is not supported on this platform.");
295   return nullptr;
296 #else
297   if (m_signals.find(signo) != m_signals.end()) {
298     error.SetErrorStringWithFormat("Signal %d already monitored.", signo);
299     return nullptr;
300   }
301 
302   SignalInfo info;
303   info.callback = callback;
304   struct sigaction new_action;
305   new_action.sa_sigaction = &SignalHandler;
306   new_action.sa_flags = SA_SIGINFO;
307   sigemptyset(&new_action.sa_mask);
308   sigaddset(&new_action.sa_mask, signo);
309   sigset_t old_set;
310 
311   g_signal_flags[signo] = 0;
312 
313   // Even if using kqueue, the signal handler will still be invoked, so it's
314   // important to replace it with our "bening" handler.
315   int ret = sigaction(signo, &new_action, &info.old_action);
316   assert(ret == 0 && "sigaction failed");
317 
318 #if HAVE_SYS_EVENT_H
319   struct kevent ev;
320   EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0);
321   ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
322   assert(ret == 0);
323 #endif
324 
325   // If we're using kqueue, the signal needs to be unblocked in order to recieve
326   // it. If using pselect/ppoll, we need to block it, and later unblock it as a
327   // part of the system call.
328   ret = pthread_sigmask(HAVE_SYS_EVENT_H ? SIG_UNBLOCK : SIG_BLOCK,
329                         &new_action.sa_mask, &old_set);
330   assert(ret == 0 && "pthread_sigmask failed");
331   info.was_blocked = sigismember(&old_set, signo);
332   m_signals.insert({signo, info});
333 
334   return SignalHandleUP(new SignalHandle(*this, signo));
335 #endif
336 }
337 
338 void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) {
339   bool erased = m_read_fds.erase(handle);
340   UNUSED_IF_ASSERT_DISABLED(erased);
341   assert(erased);
342 }
343 
344 void MainLoop::UnregisterSignal(int signo) {
345 #if SIGNAL_POLLING_UNSUPPORTED
346   Status("Signal polling is not supported on this platform.");
347 #else
348   auto it = m_signals.find(signo);
349   assert(it != m_signals.end());
350 
351   sigaction(signo, &it->second.old_action, nullptr);
352 
353   sigset_t set;
354   sigemptyset(&set);
355   sigaddset(&set, signo);
356   int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK,
357                             &set, nullptr);
358   assert(ret == 0);
359   (void)ret;
360 
361 #if HAVE_SYS_EVENT_H
362   struct kevent ev;
363   EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0);
364   ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
365   assert(ret == 0);
366 #endif
367 
368   m_signals.erase(it);
369 #endif
370 }
371 
372 Status MainLoop::Run() {
373   m_terminate_request = false;
374 
375   Status error;
376   RunImpl impl(*this);
377 
378   // run until termination or until we run out of things to listen to
379   while (!m_terminate_request && (!m_read_fds.empty() || !m_signals.empty())) {
380 
381     error = impl.Poll();
382     if (error.Fail())
383       return error;
384 
385     impl.ProcessEvents();
386 
387     if (m_terminate_request)
388       return Status();
389   }
390   return Status();
391 }
392 
393 void MainLoop::ProcessSignal(int signo) {
394   auto it = m_signals.find(signo);
395   if (it != m_signals.end())
396     it->second.callback(*this); // Do the work
397 }
398 
399 void MainLoop::ProcessReadObject(IOObject::WaitableHandle handle) {
400   auto it = m_read_fds.find(handle);
401   if (it != m_read_fds.end())
402     it->second(*this); // Do the work
403 }
404