1 //===-- MainLoop.cpp --------------------------------------------*- C++ -*-===//
3 // The LLVM Compiler Infrastructure
5 // This file is distributed under the University of Illinois Open Source
6 // License. See LICENSE.TXT for details.
8 //===----------------------------------------------------------------------===//
10 #include "llvm/Config/llvm-config.h"
12 #include "lldb/Host/MainLoop.h"
13 #include "lldb/Host/PosixApi.h"
14 #include "lldb/Utility/Status.h"
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).
28 #include <sys/event.h>
31 #elif defined(__ANDROID__)
32 #include <sys/syscall.h>
43 #if SIGNAL_POLLING_UNSUPPORTED
46 typedef int siginfo_t;
49 int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout_ts,
52 (timeout_ts == nullptr)
54 : (timeout_ts->tv_sec * 1000 + timeout_ts->tv_nsec / 1000000);
55 return POLL(fds, nfds, timeout);
61 using namespace lldb_private;
63 static sig_atomic_t g_signal_flags[NSIG];
65 static void SignalHandler(int signo, siginfo_t *info, void *) {
67 g_signal_flags[signo] = 1;
70 class MainLoop::RunImpl {
72 RunImpl(MainLoop &loop);
82 std::vector<struct kevent> in_events;
83 struct kevent out_events[4];
90 std::vector<struct pollfd> read_fds;
93 sigset_t get_sigmask();
98 MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
99 in_events.reserve(loop.m_read_fds.size());
102 Status MainLoop::RunImpl::Poll() {
103 in_events.resize(loop.m_read_fds.size());
105 for (auto &fd : loop.m_read_fds)
106 EV_SET(&in_events[i++], fd.first, EVFILT_READ, EV_ADD, 0, 0, 0);
108 num_events = kevent(loop.m_kqueue, in_events.data(), in_events.size(),
109 out_events, llvm::array_lengthof(out_events), nullptr);
112 return Status("kevent() failed with error %d\n", num_events);
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)
121 switch (out_events[i].filter) {
123 loop.ProcessReadObject(out_events[i].ident);
126 loop.ProcessSignal(out_events[i].ident);
129 llvm_unreachable("Unknown event");
134 MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) {
136 read_fds.reserve(loop.m_read_fds.size());
140 sigset_t MainLoop::RunImpl::get_sigmask() {
141 #if SIGNAL_POLLING_UNSUPPORTED
145 int ret = pthread_sigmask(SIG_SETMASK, nullptr, &sigmask);
149 for (const auto &sig : loop.m_signals)
150 sigdelset(&sigmask, sig.first);
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.
163 FD_ZERO(&read_fd_set);
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);
174 memset(&kernel_sigset, 0, sizeof(kernel_sigset));
175 kernel_sigset.set = get_sigmask();
180 } extra_data = {&kernel_sigset, sizeof(kernel_sigset)};
181 if (syscall(__NR_pselect6, nfds, &read_fd_set, nullptr, nullptr, nullptr,
182 &extra_data) == -1 &&
184 return Status(errno, eErrorTypePOSIX);
189 Status MainLoop::RunImpl::Poll() {
192 sigset_t sigmask = get_sigmask();
194 for (const auto &fd : loop.m_read_fds) {
199 read_fds.push_back(pfd);
202 if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 &&
204 return Status(errno, eErrorTypePOSIX);
210 void MainLoop::RunImpl::ProcessEvents() {
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);
221 for (const auto &handle : fds) {
223 for (const auto &fd : read_fds) {
224 if ((fd.revents & (POLLIN | POLLHUP)) == 0)
226 IOObject::WaitableHandle handle = fd.fd;
228 if (loop.m_terminate_request)
231 loop.ProcessReadObject(handle);
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);
239 for (const auto &signal : signals) {
240 if (loop.m_terminate_request)
242 g_signal_flags[signal] = 0;
243 loop.ProcessSignal(signal);
248 MainLoop::MainLoop() {
251 assert(m_kqueue >= 0);
254 MainLoop::~MainLoop() {
258 assert(m_read_fds.size() == 0);
259 assert(m_signals.size() == 0);
262 MainLoop::ReadHandleUP MainLoop::RegisterReadObject(const IOObjectSP &object_sp,
263 const Callback &callback,
266 if (object_sp->GetFdType() != IOObject:: eFDTypeSocket) {
267 error.SetErrorString("MainLoop: non-socket types unsupported on Windows");
271 if (!object_sp || !object_sp->IsValid()) {
272 error.SetErrorString("IO object is not valid.");
276 const bool inserted =
277 m_read_fds.insert({object_sp->GetWaitableHandle(), callback}).second;
279 error.SetErrorStringWithFormat("File descriptor %d already monitored.",
280 object_sp->GetWaitableHandle());
284 return CreateReadHandle(object_sp);
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.");
295 if (m_signals.find(signo) != m_signals.end()) {
296 error.SetErrorStringWithFormat("Signal %d already monitored.", signo);
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);
309 g_signal_flags[signo] = 0;
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");
318 EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0);
319 ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
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});
332 return SignalHandleUP(new SignalHandle(*this, signo));
336 void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) {
337 bool erased = m_read_fds.erase(handle);
338 UNUSED_IF_ASSERT_DISABLED(erased);
342 void MainLoop::UnregisterSignal(int signo) {
343 #if SIGNAL_POLLING_UNSUPPORTED
344 Status("Signal polling is not supported on this platform.");
346 auto it = m_signals.find(signo);
347 assert(it != m_signals.end());
349 sigaction(signo, &it->second.old_action, nullptr);
353 sigaddset(&set, signo);
354 int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK,
361 EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0);
362 ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);
370 Status MainLoop::Run() {
371 m_terminate_request = false;
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())) {
383 impl.ProcessEvents();
385 if (m_terminate_request)
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
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