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