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