Index: vendor/lldb/dist-release_80/source/Host/common/MainLoop.cpp =================================================================== --- vendor/lldb/dist-release_80/source/Host/common/MainLoop.cpp (revision 344544) +++ vendor/lldb/dist-release_80/source/Host/common/MainLoop.cpp (revision 344545) @@ -1,401 +1,407 @@ //===-- MainLoop.cpp --------------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "llvm/Config/llvm-config.h" #include "lldb/Host/MainLoop.h" #include "lldb/Host/PosixApi.h" #include "lldb/Utility/Status.h" #include #include #include #include #include #include // Multiplexing is implemented using kqueue on systems that support it (BSD // variants including OSX). On linux we use ppoll, while android uses pselect // (ppoll is present but not implemented properly). On windows we use WSApoll // (which does not support signals). #if HAVE_SYS_EVENT_H #include #elif defined(_WIN32) #include #elif defined(__ANDROID__) #include #else #include #endif #ifdef _WIN32 #define POLL WSAPoll #else #define POLL poll #endif #if SIGNAL_POLLING_UNSUPPORTED #ifdef _WIN32 typedef int sigset_t; typedef int siginfo_t; #endif int ppoll(struct pollfd *fds, size_t nfds, const struct timespec *timeout_ts, const sigset_t *) { int timeout = (timeout_ts == nullptr) ? -1 : (timeout_ts->tv_sec * 1000 + timeout_ts->tv_nsec / 1000000); return POLL(fds, nfds, timeout); } #endif using namespace lldb; using namespace lldb_private; static sig_atomic_t g_signal_flags[NSIG]; static void SignalHandler(int signo, siginfo_t *info, void *) { assert(signo < NSIG); g_signal_flags[signo] = 1; } class MainLoop::RunImpl { public: RunImpl(MainLoop &loop); ~RunImpl() = default; Status Poll(); void ProcessEvents(); private: MainLoop &loop; #if HAVE_SYS_EVENT_H std::vector in_events; struct kevent out_events[4]; int num_events = -1; #else #ifdef __ANDROID__ fd_set read_fd_set; #else std::vector read_fds; #endif sigset_t get_sigmask(); #endif }; #if HAVE_SYS_EVENT_H MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) { in_events.reserve(loop.m_read_fds.size()); } Status MainLoop::RunImpl::Poll() { in_events.resize(loop.m_read_fds.size()); unsigned i = 0; for (auto &fd : loop.m_read_fds) EV_SET(&in_events[i++], fd.first, EVFILT_READ, EV_ADD, 0, 0, 0); num_events = kevent(loop.m_kqueue, in_events.data(), in_events.size(), out_events, llvm::array_lengthof(out_events), nullptr); - if (num_events < 0) - return Status("kevent() failed with error %d\n", num_events); + if (num_events < 0) { + if (errno == EINTR) { + // in case of EINTR, let the main loop run one iteration + // we need to zero num_events to avoid assertions failing + num_events = 0; + } else + return Status(errno, eErrorTypePOSIX); + } return Status(); } void MainLoop::RunImpl::ProcessEvents() { assert(num_events >= 0); for (int i = 0; i < num_events; ++i) { if (loop.m_terminate_request) return; switch (out_events[i].filter) { case EVFILT_READ: loop.ProcessReadObject(out_events[i].ident); break; case EVFILT_SIGNAL: loop.ProcessSignal(out_events[i].ident); break; default: llvm_unreachable("Unknown event"); } } } #else MainLoop::RunImpl::RunImpl(MainLoop &loop) : loop(loop) { #ifndef __ANDROID__ read_fds.reserve(loop.m_read_fds.size()); #endif } sigset_t MainLoop::RunImpl::get_sigmask() { #if SIGNAL_POLLING_UNSUPPORTED return 0; #else sigset_t sigmask; int ret = pthread_sigmask(SIG_SETMASK, nullptr, &sigmask); assert(ret == 0); (void) ret; for (const auto &sig : loop.m_signals) sigdelset(&sigmask, sig.first); return sigmask; #endif } #ifdef __ANDROID__ Status MainLoop::RunImpl::Poll() { // ppoll(2) is not supported on older all android versions. Also, older // versions android (API <= 19) implemented pselect in a non-atomic way, as a // combination of pthread_sigmask and select. This is not sufficient for us, // as we rely on the atomicity to correctly implement signal polling, so we // call the underlying syscall ourselves. FD_ZERO(&read_fd_set); int nfds = 0; for (const auto &fd : loop.m_read_fds) { FD_SET(fd.first, &read_fd_set); nfds = std::max(nfds, fd.first + 1); } union { sigset_t set; uint64_t pad; } kernel_sigset; memset(&kernel_sigset, 0, sizeof(kernel_sigset)); kernel_sigset.set = get_sigmask(); struct { void *sigset_ptr; size_t sigset_len; } extra_data = {&kernel_sigset, sizeof(kernel_sigset)}; if (syscall(__NR_pselect6, nfds, &read_fd_set, nullptr, nullptr, nullptr, &extra_data) == -1 && errno != EINTR) return Status(errno, eErrorTypePOSIX); return Status(); } #else Status MainLoop::RunImpl::Poll() { read_fds.clear(); sigset_t sigmask = get_sigmask(); for (const auto &fd : loop.m_read_fds) { struct pollfd pfd; pfd.fd = fd.first; pfd.events = POLLIN; pfd.revents = 0; read_fds.push_back(pfd); } if (ppoll(read_fds.data(), read_fds.size(), nullptr, &sigmask) == -1 && errno != EINTR) return Status(errno, eErrorTypePOSIX); return Status(); } #endif void MainLoop::RunImpl::ProcessEvents() { #ifdef __ANDROID__ // Collect first all readable file descriptors into a separate vector and // then iterate over it to invoke callbacks. Iterating directly over // loop.m_read_fds is not possible because the callbacks can modify the // container which could invalidate the iterator. std::vector fds; for (const auto &fd : loop.m_read_fds) if (FD_ISSET(fd.first, &read_fd_set)) fds.push_back(fd.first); for (const auto &handle : fds) { #else for (const auto &fd : read_fds) { if ((fd.revents & (POLLIN | POLLHUP)) == 0) continue; IOObject::WaitableHandle handle = fd.fd; #endif if (loop.m_terminate_request) return; loop.ProcessReadObject(handle); } std::vector signals; for (const auto &entry : loop.m_signals) if (g_signal_flags[entry.first] != 0) signals.push_back(entry.first); for (const auto &signal : signals) { if (loop.m_terminate_request) return; g_signal_flags[signal] = 0; loop.ProcessSignal(signal); } } #endif MainLoop::MainLoop() { #if HAVE_SYS_EVENT_H m_kqueue = kqueue(); assert(m_kqueue >= 0); #endif } MainLoop::~MainLoop() { #if HAVE_SYS_EVENT_H close(m_kqueue); #endif assert(m_read_fds.size() == 0); assert(m_signals.size() == 0); } MainLoop::ReadHandleUP MainLoop::RegisterReadObject(const IOObjectSP &object_sp, const Callback &callback, Status &error) { #ifdef _WIN32 if (object_sp->GetFdType() != IOObject:: eFDTypeSocket) { error.SetErrorString("MainLoop: non-socket types unsupported on Windows"); return nullptr; } #endif if (!object_sp || !object_sp->IsValid()) { error.SetErrorString("IO object is not valid."); return nullptr; } const bool inserted = m_read_fds.insert({object_sp->GetWaitableHandle(), callback}).second; if (!inserted) { error.SetErrorStringWithFormat("File descriptor %d already monitored.", object_sp->GetWaitableHandle()); return nullptr; } return CreateReadHandle(object_sp); } // We shall block the signal, then install the signal handler. The signal will // be unblocked in the Run() function to check for signal delivery. MainLoop::SignalHandleUP MainLoop::RegisterSignal(int signo, const Callback &callback, Status &error) { #ifdef SIGNAL_POLLING_UNSUPPORTED error.SetErrorString("Signal polling is not supported on this platform."); return nullptr; #else if (m_signals.find(signo) != m_signals.end()) { error.SetErrorStringWithFormat("Signal %d already monitored.", signo); return nullptr; } SignalInfo info; info.callback = callback; struct sigaction new_action; new_action.sa_sigaction = &SignalHandler; new_action.sa_flags = SA_SIGINFO; sigemptyset(&new_action.sa_mask); sigaddset(&new_action.sa_mask, signo); sigset_t old_set; g_signal_flags[signo] = 0; // Even if using kqueue, the signal handler will still be invoked, so it's // important to replace it with our "benign" handler. int ret = sigaction(signo, &new_action, &info.old_action); assert(ret == 0 && "sigaction failed"); #if HAVE_SYS_EVENT_H struct kevent ev; EV_SET(&ev, signo, EVFILT_SIGNAL, EV_ADD, 0, 0, 0); ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr); assert(ret == 0); #endif // If we're using kqueue, the signal needs to be unblocked in order to // receive it. If using pselect/ppoll, we need to block it, and later unblock // it as a part of the system call. ret = pthread_sigmask(HAVE_SYS_EVENT_H ? SIG_UNBLOCK : SIG_BLOCK, &new_action.sa_mask, &old_set); assert(ret == 0 && "pthread_sigmask failed"); info.was_blocked = sigismember(&old_set, signo); m_signals.insert({signo, info}); return SignalHandleUP(new SignalHandle(*this, signo)); #endif } void MainLoop::UnregisterReadObject(IOObject::WaitableHandle handle) { bool erased = m_read_fds.erase(handle); UNUSED_IF_ASSERT_DISABLED(erased); assert(erased); } void MainLoop::UnregisterSignal(int signo) { #if SIGNAL_POLLING_UNSUPPORTED Status("Signal polling is not supported on this platform."); #else auto it = m_signals.find(signo); assert(it != m_signals.end()); sigaction(signo, &it->second.old_action, nullptr); sigset_t set; sigemptyset(&set); sigaddset(&set, signo); int ret = pthread_sigmask(it->second.was_blocked ? SIG_BLOCK : SIG_UNBLOCK, &set, nullptr); assert(ret == 0); (void)ret; #if HAVE_SYS_EVENT_H struct kevent ev; EV_SET(&ev, signo, EVFILT_SIGNAL, EV_DELETE, 0, 0, 0); ret = kevent(m_kqueue, &ev, 1, nullptr, 0, nullptr); assert(ret == 0); #endif m_signals.erase(it); #endif } Status MainLoop::Run() { m_terminate_request = false; Status error; RunImpl impl(*this); // run until termination or until we run out of things to listen to while (!m_terminate_request && (!m_read_fds.empty() || !m_signals.empty())) { error = impl.Poll(); if (error.Fail()) return error; impl.ProcessEvents(); if (m_terminate_request) return Status(); } return Status(); } void MainLoop::ProcessSignal(int signo) { auto it = m_signals.find(signo); if (it != m_signals.end()) it->second.callback(*this); // Do the work } void MainLoop::ProcessReadObject(IOObject::WaitableHandle handle) { auto it = m_read_fds.find(handle); if (it != m_read_fds.end()) it->second(*this); // Do the work } Index: vendor/lldb/dist-release_80/source/Host/openbsd/Host.cpp =================================================================== --- vendor/lldb/dist-release_80/source/Host/openbsd/Host.cpp (revision 344544) +++ vendor/lldb/dist-release_80/source/Host/openbsd/Host.cpp (revision 344545) @@ -1,217 +1,216 @@ //===-- source/Host/openbsd/Host.cpp ----------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include #include #include #include #include #include #include #include #include "lldb/Host/Host.h" #include "lldb/Host/HostInfo.h" #include "lldb/Target/Process.h" #include "lldb/Utility/DataBufferHeap.h" #include "lldb/Utility/DataExtractor.h" #include "lldb/Utility/Endian.h" #include "lldb/Utility/Log.h" #include "lldb/Utility/NameMatches.h" #include "lldb/Utility/Status.h" #include "lldb/Utility/StreamString.h" #include "llvm/Support/Host.h" extern "C" { extern char **environ; } using namespace lldb; using namespace lldb_private; Environment Host::GetEnvironment() { Environment env; char *v; char **var = environ; for (; var != NULL && *var != NULL; ++var) { v = strchr(*var, (int)'-'); if (v == NULL) continue; env.insert(v); } return env; } static bool GetOpenBSDProcessArgs(const ProcessInstanceInfoMatch *match_info_ptr, ProcessInstanceInfo &process_info) { if (process_info.ProcessIDIsValid()) { int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_ARGS, (int)process_info.GetProcessID()}; char arg_data[8192]; size_t arg_data_size = sizeof(arg_data); if (::sysctl(mib, 4, arg_data, &arg_data_size, NULL, 0) == 0) { DataExtractor data(arg_data, arg_data_size, endian::InlHostByteOrder(), sizeof(void *)); lldb::offset_t offset = 0; const char *cstr; cstr = data.GetCStr(&offset); if (cstr) { - process_info.GetExecutableFile().SetFile(cstr, false, - FileSpec::Style::native); + process_info.GetExecutableFile().SetFile(cstr, FileSpec::Style::native); if (!(match_info_ptr == NULL || NameMatches( process_info.GetExecutableFile().GetFilename().GetCString(), match_info_ptr->GetNameMatchType(), match_info_ptr->GetProcessInfo().GetName()))) return false; Args &proc_args = process_info.GetArguments(); while (1) { const uint8_t *p = data.PeekData(offset, 1); while ((p != NULL) && (*p == '\0') && offset < arg_data_size) { ++offset; p = data.PeekData(offset, 1); } if (p == NULL || offset >= arg_data_size) return true; cstr = data.GetCStr(&offset); if (cstr) proc_args.AppendArgument(llvm::StringRef(cstr)); else return true; } } } } return false; } static bool GetOpenBSDProcessCPUType(ProcessInstanceInfo &process_info) { if (process_info.ProcessIDIsValid()) { process_info.GetArchitecture() = HostInfo::GetArchitecture(HostInfo::eArchKindDefault); return true; } process_info.GetArchitecture().Clear(); return false; } static bool GetOpenBSDProcessUserAndGroup(ProcessInstanceInfo &process_info) { struct kinfo_proc proc_kinfo; size_t proc_kinfo_size; if (process_info.ProcessIDIsValid()) { int mib[4] = {CTL_KERN, KERN_PROC, KERN_PROC_PID, (int)process_info.GetProcessID()}; proc_kinfo_size = sizeof(struct kinfo_proc); if (::sysctl(mib, 4, &proc_kinfo, &proc_kinfo_size, NULL, 0) == 0) { if (proc_kinfo_size > 0) { process_info.SetParentProcessID(proc_kinfo.p_ppid); process_info.SetUserID(proc_kinfo.p_ruid); process_info.SetGroupID(proc_kinfo.p_rgid); process_info.SetEffectiveUserID(proc_kinfo.p_uid); process_info.SetEffectiveGroupID(proc_kinfo.p_gid); return true; } } } process_info.SetParentProcessID(LLDB_INVALID_PROCESS_ID); process_info.SetUserID(UINT32_MAX); process_info.SetGroupID(UINT32_MAX); process_info.SetEffectiveUserID(UINT32_MAX); process_info.SetEffectiveGroupID(UINT32_MAX); return false; } uint32_t Host::FindProcesses(const ProcessInstanceInfoMatch &match_info, ProcessInstanceInfoList &process_infos) { std::vector kinfos; int mib[3] = {CTL_KERN, KERN_PROC, KERN_PROC_ALL}; size_t pid_data_size = 0; if (::sysctl(mib, 3, NULL, &pid_data_size, NULL, 0) != 0) return 0; // Add a few extra in case a few more show up const size_t estimated_pid_count = (pid_data_size / sizeof(struct kinfo_proc)) + 10; kinfos.resize(estimated_pid_count); pid_data_size = kinfos.size() * sizeof(struct kinfo_proc); if (::sysctl(mib, 3, &kinfos[0], &pid_data_size, NULL, 0) != 0) return 0; const size_t actual_pid_count = (pid_data_size / sizeof(struct kinfo_proc)); bool all_users = match_info.GetMatchAllUsers(); const ::pid_t our_pid = getpid(); const uid_t our_uid = getuid(); for (size_t i = 0; i < actual_pid_count; i++) { const struct kinfo_proc &kinfo = kinfos[i]; const bool kinfo_user_matches = (all_users || (kinfo.p_ruid == our_uid) || // Special case, if lldb is being run as // root we can attach to anything. (our_uid == 0)); if (kinfo_user_matches == false || // Make sure the user is acceptable kinfo.p_pid == our_pid || // Skip this process kinfo.p_pid == 0 || // Skip kernel (kernel pid is zero) kinfo.p_stat == SZOMB || // Zombies are bad, they like brains... kinfo.p_psflags & PS_TRACED || // Being debugged? kinfo.p_flag & P_WEXIT) // Working on exiting continue; ProcessInstanceInfo process_info; process_info.SetProcessID(kinfo.p_pid); process_info.SetParentProcessID(kinfo.p_ppid); process_info.SetUserID(kinfo.p_ruid); process_info.SetGroupID(kinfo.p_rgid); process_info.SetEffectiveUserID(kinfo.p_svuid); process_info.SetEffectiveGroupID(kinfo.p_svgid); // Make sure our info matches before we go fetch the name and cpu type if (match_info.Matches(process_info) && GetOpenBSDProcessArgs(&match_info, process_info)) { GetOpenBSDProcessCPUType(process_info); if (match_info.Matches(process_info)) process_infos.Append(process_info); } } return process_infos.GetSize(); } bool Host::GetProcessInfo(lldb::pid_t pid, ProcessInstanceInfo &process_info) { process_info.SetProcessID(pid); if (GetOpenBSDProcessArgs(NULL, process_info)) { // should use libprocstat instead of going right into sysctl? GetOpenBSDProcessCPUType(process_info); GetOpenBSDProcessUserAndGroup(process_info); return true; } process_info.Clear(); return false; } Status Host::ShellExpandArguments(ProcessLaunchInfo &launch_info) { return Status("unimplemented"); } Index: vendor/lldb/dist-release_80/unittests/Host/MainLoopTest.cpp =================================================================== --- vendor/lldb/dist-release_80/unittests/Host/MainLoopTest.cpp (revision 344544) +++ vendor/lldb/dist-release_80/unittests/Host/MainLoopTest.cpp (revision 344545) @@ -1,140 +1,164 @@ //===-- MainLoopTest.cpp ----------------------------------------*- C++ -*-===// // // The LLVM Compiler Infrastructure // // This file is distributed under the University of Illinois Open Source // License. See LICENSE.TXT for details. // //===----------------------------------------------------------------------===// #include "lldb/Host/MainLoop.h" #include "lldb/Host/ConnectionFileDescriptor.h" #include "lldb/Host/PseudoTerminal.h" #include "lldb/Host/common/TCPSocket.h" #include "gtest/gtest.h" #include using namespace lldb_private; namespace { class MainLoopTest : public testing::Test { public: static void SetUpTestCase() { #ifdef _MSC_VER WSADATA data; ASSERT_EQ(0, WSAStartup(MAKEWORD(2, 2), &data)); #endif } static void TearDownTestCase() { #ifdef _MSC_VER ASSERT_EQ(0, WSACleanup()); #endif } void SetUp() override { bool child_processes_inherit = false; Status error; std::unique_ptr listen_socket_up( new TCPSocket(true, child_processes_inherit)); ASSERT_TRUE(error.Success()); error = listen_socket_up->Listen("localhost:0", 5); ASSERT_TRUE(error.Success()); Socket *accept_socket; std::future accept_error = std::async(std::launch::async, [&] { return listen_socket_up->Accept(accept_socket); }); std::unique_ptr connect_socket_up( new TCPSocket(true, child_processes_inherit)); error = connect_socket_up->Connect( llvm::formatv("localhost:{0}", listen_socket_up->GetLocalPortNumber()) .str()); ASSERT_TRUE(error.Success()); ASSERT_TRUE(accept_error.get().Success()); callback_count = 0; socketpair[0] = std::move(connect_socket_up); socketpair[1].reset(accept_socket); } void TearDown() override { socketpair[0].reset(); socketpair[1].reset(); } protected: MainLoop::Callback make_callback() { return [&](MainLoopBase &loop) { ++callback_count; loop.RequestTermination(); }; } std::shared_ptr socketpair[2]; unsigned callback_count; }; } // namespace TEST_F(MainLoopTest, ReadObject) { char X = 'X'; size_t len = sizeof(X); ASSERT_TRUE(socketpair[0]->Write(&X, len).Success()); MainLoop loop; Status error; auto handle = loop.RegisterReadObject(socketpair[1], make_callback(), error); ASSERT_TRUE(error.Success()); ASSERT_TRUE(handle); ASSERT_TRUE(loop.Run().Success()); ASSERT_EQ(1u, callback_count); } TEST_F(MainLoopTest, TerminatesImmediately) { char X = 'X'; size_t len = sizeof(X); ASSERT_TRUE(socketpair[0]->Write(&X, len).Success()); ASSERT_TRUE(socketpair[1]->Write(&X, len).Success()); MainLoop loop; Status error; auto handle0 = loop.RegisterReadObject(socketpair[0], make_callback(), error); ASSERT_TRUE(error.Success()); auto handle1 = loop.RegisterReadObject(socketpair[1], make_callback(), error); ASSERT_TRUE(error.Success()); ASSERT_TRUE(loop.Run().Success()); ASSERT_EQ(1u, callback_count); } #ifdef LLVM_ON_UNIX TEST_F(MainLoopTest, DetectsEOF) { PseudoTerminal term; ASSERT_TRUE(term.OpenFirstAvailableMaster(O_RDWR, nullptr, 0)); ASSERT_TRUE(term.OpenSlave(O_RDWR | O_NOCTTY, nullptr, 0)); auto conn = llvm::make_unique( term.ReleaseMasterFileDescriptor(), true); Status error; MainLoop loop; auto handle = loop.RegisterReadObject(conn->GetReadObject(), make_callback(), error); ASSERT_TRUE(error.Success()); term.CloseSlaveFileDescriptor(); ASSERT_TRUE(loop.Run().Success()); ASSERT_EQ(1u, callback_count); } TEST_F(MainLoopTest, Signal) { MainLoop loop; Status error; auto handle = loop.RegisterSignal(SIGUSR1, make_callback(), error); ASSERT_TRUE(error.Success()); kill(getpid(), SIGUSR1); ASSERT_TRUE(loop.Run().Success()); ASSERT_EQ(1u, callback_count); } + +// Test that a signal which is not monitored by the MainLoop does not +// cause a premature exit. +TEST_F(MainLoopTest, UnmonitoredSignal) { + MainLoop loop; + Status error; + struct sigaction sa; + sa.sa_sigaction = [](int, siginfo_t *, void *) { }; + sa.sa_flags = SA_SIGINFO; // important: no SA_RESTART + sigemptyset(&sa.sa_mask); + ASSERT_EQ(0, sigaction(SIGUSR2, &sa, nullptr)); + + auto handle = loop.RegisterSignal(SIGUSR1, make_callback(), error); + ASSERT_TRUE(error.Success()); + std::thread killer([]() { + sleep(1); + kill(getpid(), SIGUSR2); + sleep(1); + kill(getpid(), SIGUSR1); + }); + ASSERT_TRUE(loop.Run().Success()); + killer.join(); + ASSERT_EQ(1u, callback_count); +} #endif