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 sigset_t sigmask; 141 #if defined(_WIN32) 142 sigmask = 0; 143 #elif SIGNAL_POLLING_UNSUPPORTED 144 sigemptyset(&sigmask); 145 #else 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 #endif 153 return sigmask; 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 214 // then 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 | POLLHUP)) == 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 _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 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 "benign" 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 325 // receive it. If using pselect/ppoll, we need to block it, and later unblock 326 // it as a 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