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(LLVM_ON_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 LLVM_ON_WIN32 38 #define POLL WSAPoll 39 #else 40 #define POLL poll 41 #endif 42 43 #if SIGNAL_POLLING_UNSUPPORTED 44 #ifdef LLVM_ON_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 then 213 // 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 LLVM_ON_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 289 // the Run() function to check for signal delivery. 290 MainLoop::SignalHandleUP 291 MainLoop::RegisterSignal(int signo, const Callback &callback, Status &error) { 292 #ifdef SIGNAL_POLLING_UNSUPPORTED 293 error.SetErrorString("Signal polling is not supported on this platform."); 294 return nullptr; 295 #else 296 if (m_signals.find(signo) != m_signals.end()) { 297 error.SetErrorStringWithFormat("Signal %d already monitored.", signo); 298 return nullptr; 299 } 300 301 SignalInfo info; 302 info.callback = callback; 303 struct sigaction new_action; 304 new_action.sa_sigaction = &SignalHandler; 305 new_action.sa_flags = SA_SIGINFO; 306 sigemptyset(&new_action.sa_mask); 307 sigaddset(&new_action.sa_mask, signo); 308 sigset_t old_set; 309 310 g_signal_flags[signo] = 0; 311 312 // Even if using kqueue, the signal handler will still be invoked, so it's 313 // important to replace it with our "bening" handler. 314 int ret = sigaction(signo, &new_action, &info.old_action); 315 assert(ret == 0 && "sigaction failed"); 316 317 #if HAVE_SYS_EVENT_H 318 struct kevent ev; 319 EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0); 320 ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr); 321 assert(ret == 0); 322 #endif 323 324 // If we're using kqueue, the signal needs to be unblocked in order to recieve 325 // it. If using pselect/ppoll, we need to block it, and later unblock it as a 326 // part of the system call. 327 ret = pthread_sigmask(HAVE_SYS_EVENT_H ? SIG_UNBLOCK : SIG_BLOCK, 328 &new_action.sa_mask, &old_set); 329 assert(ret == 0 && "pthread_sigmask failed"); 330 info.was_blocked = sigismember(&old_set, signo); 331 m_signals.insert({signo, info}); 332 333 return SignalHandleUP(new SignalHandle(*this, signo)); 334 #endif 335 } 336 337 void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) { 338 bool erased = m_read_fds.erase(handle); 339 UNUSED_IF_ASSERT_DISABLED(erased); 340 assert(erased); 341 } 342 343 void MainLoop::UnregisterSignal(int signo) { 344 #if SIGNAL_POLLING_UNSUPPORTED 345 Status("Signal polling is not supported on this platform."); 346 #else 347 auto it = m_signals.find(signo); 348 assert(it != m_signals.end()); 349 350 sigaction(signo, &it->second.old_action, nullptr); 351 352 sigset_t set; 353 sigemptyset(&set); 354 sigaddset(&set, signo); 355 int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK, 356 &set, nullptr); 357 assert(ret == 0); 358 (void)ret; 359 360 #if HAVE_SYS_EVENT_H 361 struct kevent ev; 362 EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0); 363 ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr); 364 assert(ret == 0); 365 #endif 366 367 m_signals.erase(it); 368 #endif 369 } 370 371 Status MainLoop::Run() { 372 m_terminate_request = false; 373 374 Status error; 375 RunImpl impl(*this); 376 377 // run until termination or until we run out of things to listen to 378 while (!m_terminate_request && (!m_read_fds.empty() || !m_signals.empty())) { 379 380 error = impl.Poll(); 381 if (error.Fail()) 382 return error; 383 384 impl.ProcessEvents(); 385 386 if (m_terminate_request) 387 return Status(); 388 } 389 return Status(); 390 } 391 392 void MainLoop::ProcessSignal(int signo) { 393 auto it = m_signals.find(signo); 394 if (it != m_signals.end()) 395 it->second.callback(*this); // Do the work 396 } 397 398 void MainLoop::ProcessReadObject(IOObject::WaitableHandle handle) { 399 auto it = m_read_fds.find(handle); 400 if (it != m_read_fds.end()) 401 it->second(*this); // Do the work 402 } 403