Path: blob/main/contrib/llvm-project/lldb/source/Host/posix/MainLoopPosix.cpp
39607 views
//===-- MainLoopPosix.cpp -------------------------------------------------===//1//2// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.3// See https://llvm.org/LICENSE.txt for license information.4// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception5//6//===----------------------------------------------------------------------===//78#include "lldb/Host/posix/MainLoopPosix.h"9#include "lldb/Host/Config.h"10#include "lldb/Host/PosixApi.h"11#include "lldb/Utility/Status.h"12#include "llvm/Config/llvm-config.h"13#include "llvm/Support/Errno.h"14#include <algorithm>15#include <cassert>16#include <cerrno>17#include <csignal>18#include <ctime>19#include <vector>2021// Multiplexing is implemented using kqueue on systems that support it (BSD22// variants including OSX). On linux we use ppoll, while android uses pselect23// (ppoll is present but not implemented properly). On windows we use WSApoll24// (which does not support signals).2526#if HAVE_SYS_EVENT_H27#include <sys/event.h>28#elif defined(__ANDROID__)29#include <sys/syscall.h>30#else31#include <poll.h>32#endif3334using namespace lldb;35using namespace lldb_private;3637static sig_atomic_t g_signal_flags[NSIG];3839static void SignalHandler(int signo, siginfo_t *info, void *) {40assert(signo < NSIG);41g_signal_flags[signo] = 1;42}4344class MainLoopPosix::RunImpl {45public:46RunImpl(MainLoopPosix &loop);47~RunImpl() = default;4849Status Poll();50void ProcessEvents();5152private:53MainLoopPosix &loop;5455#if HAVE_SYS_EVENT_H56std::vector<struct kevent> in_events;57struct kevent out_events[4];58int num_events = -1;5960#else61#ifdef __ANDROID__62fd_set read_fd_set;63#else64std::vector<struct pollfd> read_fds;65#endif6667sigset_t get_sigmask();68#endif69};7071#if HAVE_SYS_EVENT_H72MainLoopPosix::RunImpl::RunImpl(MainLoopPosix &loop) : loop(loop) {73in_events.reserve(loop.m_read_fds.size());74}7576Status MainLoopPosix::RunImpl::Poll() {77in_events.resize(loop.m_read_fds.size());78unsigned i = 0;79for (auto &fd : loop.m_read_fds)80EV_SET(&in_events[i++], fd.first, EVFILT_READ, EV_ADD, 0, 0, 0);8182num_events = kevent(loop.m_kqueue, in_events.data(), in_events.size(),83out_events, std::size(out_events), nullptr);8485if (num_events < 0) {86if (errno == EINTR) {87// in case of EINTR, let the main loop run one iteration88// we need to zero num_events to avoid assertions failing89num_events = 0;90} else91return Status(errno, eErrorTypePOSIX);92}93return Status();94}9596void MainLoopPosix::RunImpl::ProcessEvents() {97assert(num_events >= 0);98for (int i = 0; i < num_events; ++i) {99if (loop.m_terminate_request)100return;101switch (out_events[i].filter) {102case EVFILT_READ:103loop.ProcessReadObject(out_events[i].ident);104break;105case EVFILT_SIGNAL:106loop.ProcessSignal(out_events[i].ident);107break;108default:109llvm_unreachable("Unknown event");110}111}112}113#else114MainLoopPosix::RunImpl::RunImpl(MainLoopPosix &loop) : loop(loop) {115#ifndef __ANDROID__116read_fds.reserve(loop.m_read_fds.size());117#endif118}119120sigset_t MainLoopPosix::RunImpl::get_sigmask() {121sigset_t sigmask;122int ret = pthread_sigmask(SIG_SETMASK, nullptr, &sigmask);123assert(ret == 0);124UNUSED_IF_ASSERT_DISABLED(ret);125126for (const auto &sig : loop.m_signals)127sigdelset(&sigmask, sig.first);128return sigmask;129}130131#ifdef __ANDROID__132Status MainLoopPosix::RunImpl::Poll() {133// ppoll(2) is not supported on older all android versions. Also, older134// versions android (API <= 19) implemented pselect in a non-atomic way, as a135// combination of pthread_sigmask and select. This is not sufficient for us,136// as we rely on the atomicity to correctly implement signal polling, so we137// call the underlying syscall ourselves.138139FD_ZERO(&read_fd_set);140int nfds = 0;141for (const auto &fd : loop.m_read_fds) {142FD_SET(fd.first, &read_fd_set);143nfds = std::max(nfds, fd.first + 1);144}145146union {147sigset_t set;148uint64_t pad;149} kernel_sigset;150memset(&kernel_sigset, 0, sizeof(kernel_sigset));151kernel_sigset.set = get_sigmask();152153struct {154void *sigset_ptr;155size_t sigset_len;156} extra_data = {&kernel_sigset, sizeof(kernel_sigset)};157if (syscall(__NR_pselect6, nfds, &read_fd_set, nullptr, nullptr, nullptr,158&extra_data) == -1) {159if (errno != EINTR)160return Status(errno, eErrorTypePOSIX);161else162FD_ZERO(&read_fd_set);163}164165return Status();166}167#else168Status MainLoopPosix::RunImpl::Poll() {169read_fds.clear();170171sigset_t sigmask = get_sigmask();172173for (const auto &fd : loop.m_read_fds) {174struct pollfd pfd;175pfd.fd = fd.first;176pfd.events = POLLIN;177pfd.revents = 0;178read_fds.push_back(pfd);179}180181if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 &&182errno != EINTR)183return Status(errno, eErrorTypePOSIX);184185return Status();186}187#endif188189void MainLoopPosix::RunImpl::ProcessEvents() {190#ifdef __ANDROID__191// Collect first all readable file descriptors into a separate vector and192// then iterate over it to invoke callbacks. Iterating directly over193// loop.m_read_fds is not possible because the callbacks can modify the194// container which could invalidate the iterator.195std::vector<IOObject::WaitableHandle> fds;196for (const auto &fd : loop.m_read_fds)197if (FD_ISSET(fd.first, &read_fd_set))198fds.push_back(fd.first);199200for (const auto &handle : fds) {201#else202for (const auto &fd : read_fds) {203if ((fd.revents & (POLLIN | POLLHUP)) == 0)204continue;205IOObject::WaitableHandle handle = fd.fd;206#endif207if (loop.m_terminate_request)208return;209210loop.ProcessReadObject(handle);211}212213std::vector<int> signals;214for (const auto &entry : loop.m_signals)215if (g_signal_flags[entry.first] != 0)216signals.push_back(entry.first);217218for (const auto &signal : signals) {219if (loop.m_terminate_request)220return;221g_signal_flags[signal] = 0;222loop.ProcessSignal(signal);223}224}225#endif226227MainLoopPosix::MainLoopPosix() : m_triggering(false) {228Status error = m_trigger_pipe.CreateNew(/*child_process_inherit=*/false);229assert(error.Success());230const int trigger_pipe_fd = m_trigger_pipe.GetReadFileDescriptor();231m_read_fds.insert({trigger_pipe_fd, [trigger_pipe_fd](MainLoopBase &loop) {232char c;233ssize_t bytes_read = llvm::sys::RetryAfterSignal(234-1, ::read, trigger_pipe_fd, &c, 1);235assert(bytes_read == 1);236UNUSED_IF_ASSERT_DISABLED(bytes_read);237// NB: This implicitly causes another loop iteration238// and therefore the execution of pending callbacks.239}});240#if HAVE_SYS_EVENT_H241m_kqueue = kqueue();242assert(m_kqueue >= 0);243#endif244}245246MainLoopPosix::~MainLoopPosix() {247#if HAVE_SYS_EVENT_H248close(m_kqueue);249#endif250m_read_fds.erase(m_trigger_pipe.GetReadFileDescriptor());251m_trigger_pipe.Close();252assert(m_read_fds.size() == 0);253assert(m_signals.size() == 0);254}255256MainLoopPosix::ReadHandleUP257MainLoopPosix::RegisterReadObject(const IOObjectSP &object_sp,258const Callback &callback, Status &error) {259if (!object_sp || !object_sp->IsValid()) {260error.SetErrorString("IO object is not valid.");261return nullptr;262}263264const bool inserted =265m_read_fds.insert({object_sp->GetWaitableHandle(), callback}).second;266if (!inserted) {267error.SetErrorStringWithFormat("File descriptor %d already monitored.",268object_sp->GetWaitableHandle());269return nullptr;270}271272return CreateReadHandle(object_sp);273}274275// We shall block the signal, then install the signal handler. The signal will276// be unblocked in the Run() function to check for signal delivery.277MainLoopPosix::SignalHandleUP278MainLoopPosix::RegisterSignal(int signo, const Callback &callback,279Status &error) {280auto signal_it = m_signals.find(signo);281if (signal_it != m_signals.end()) {282auto callback_it = signal_it->second.callbacks.insert(283signal_it->second.callbacks.end(), callback);284return SignalHandleUP(new SignalHandle(*this, signo, callback_it));285}286287SignalInfo info;288info.callbacks.push_back(callback);289struct sigaction new_action;290new_action.sa_sigaction = &SignalHandler;291new_action.sa_flags = SA_SIGINFO;292sigemptyset(&new_action.sa_mask);293sigaddset(&new_action.sa_mask, signo);294sigset_t old_set;295296g_signal_flags[signo] = 0;297298// Even if using kqueue, the signal handler will still be invoked, so it's299// important to replace it with our "benign" handler.300int ret = sigaction(signo, &new_action, &info.old_action);301UNUSED_IF_ASSERT_DISABLED(ret);302assert(ret == 0 && "sigaction failed");303304#if HAVE_SYS_EVENT_H305struct kevent ev;306EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0);307ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);308assert(ret == 0);309#endif310311// If we're using kqueue, the signal needs to be unblocked in order to312// receive it. If using pselect/ppoll, we need to block it, and later unblock313// it as a part of the system call.314ret = pthread_sigmask(HAVE_SYS_EVENT_H ? SIG_UNBLOCK : SIG_BLOCK,315&new_action.sa_mask, &old_set);316assert(ret == 0 && "pthread_sigmask failed");317info.was_blocked = sigismember(&old_set, signo);318auto insert_ret = m_signals.insert({signo, info});319320return SignalHandleUP(new SignalHandle(321*this, signo, insert_ret.first->second.callbacks.begin()));322}323324void MainLoopPosix::UnregisterReadObject(IOObject::WaitableHandle handle) {325bool erased = m_read_fds.erase(handle);326UNUSED_IF_ASSERT_DISABLED(erased);327assert(erased);328}329330void MainLoopPosix::UnregisterSignal(331int signo, std::list<Callback>::iterator callback_it) {332auto it = m_signals.find(signo);333assert(it != m_signals.end());334335it->second.callbacks.erase(callback_it);336// Do not remove the signal handler unless all callbacks have been erased.337if (!it->second.callbacks.empty())338return;339340sigaction(signo, &it->second.old_action, nullptr);341342sigset_t set;343sigemptyset(&set);344sigaddset(&set, signo);345int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK,346&set, nullptr);347assert(ret == 0);348UNUSED_IF_ASSERT_DISABLED(ret);349350#if HAVE_SYS_EVENT_H351struct kevent ev;352EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0);353ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr);354assert(ret == 0);355#endif356357m_signals.erase(it);358}359360Status MainLoopPosix::Run() {361m_terminate_request = false;362363Status error;364RunImpl impl(*this);365366// run until termination or until we run out of things to listen to367// (m_read_fds will always contain m_trigger_pipe fd, so check for > 1)368while (!m_terminate_request &&369(m_read_fds.size() > 1 || !m_signals.empty())) {370error = impl.Poll();371if (error.Fail())372return error;373374impl.ProcessEvents();375376m_triggering = false;377ProcessPendingCallbacks();378}379return Status();380}381382void MainLoopPosix::ProcessReadObject(IOObject::WaitableHandle handle) {383auto it = m_read_fds.find(handle);384if (it != m_read_fds.end())385it->second(*this); // Do the work386}387388void MainLoopPosix::ProcessSignal(int signo) {389auto it = m_signals.find(signo);390if (it != m_signals.end()) {391// The callback may actually register/unregister signal handlers,392// so we need to create a copy first.393llvm::SmallVector<Callback, 4> callbacks_to_run{394it->second.callbacks.begin(), it->second.callbacks.end()};395for (auto &x : callbacks_to_run)396x(*this); // Do the work397}398}399400void MainLoopPosix::TriggerPendingCallbacks() {401if (m_triggering.exchange(true))402return;403404char c = '.';405size_t bytes_written;406Status error = m_trigger_pipe.Write(&c, 1, bytes_written);407assert(error.Success());408UNUSED_IF_ASSERT_DISABLED(error);409assert(bytes_written == 1);410}411412413