Path: blob/main/contrib/llvm-project/lldb/source/Utility/Broadcaster.cpp
39587 views
//===-- Broadcaster.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/Utility/Broadcaster.h"9#include "lldb/Utility/Event.h"10#include "lldb/Utility/LLDBLog.h"11#include "lldb/Utility/Listener.h"12#include "lldb/Utility/Stream.h"13#include "lldb/Utility/StreamString.h"1415#include <algorithm>16#include <memory>17#include <utility>1819#include <cassert>20#include <cstddef>2122using namespace lldb;23using namespace lldb_private;2425Broadcaster::Broadcaster(BroadcasterManagerSP manager_sp, std::string name)26: m_broadcaster_sp(std::make_shared<BroadcasterImpl>(*this)),27m_manager_sp(std::move(manager_sp)), m_broadcaster_name(std::move(name)) {28Log *log = GetLog(LLDBLog::Object);29LLDB_LOG(log, "{0} Broadcaster::Broadcaster(\"{1}\")",30static_cast<void *>(this), GetBroadcasterName());31}3233Broadcaster::BroadcasterImpl::BroadcasterImpl(Broadcaster &broadcaster)34: m_broadcaster(broadcaster), m_listeners(), m_listeners_mutex(),35m_hijacking_listeners(), m_hijacking_masks() {}3637Broadcaster::~Broadcaster() {38Log *log = GetLog(LLDBLog::Object);39LLDB_LOG(log, "{0} Broadcaster::~Broadcaster(\"{1}\")",40static_cast<void *>(this), GetBroadcasterName());4142Clear();43}4445void Broadcaster::CheckInWithManager() {46if (m_manager_sp) {47m_manager_sp->SignUpListenersForBroadcaster(*this);48}49}5051llvm::SmallVector<std::pair<ListenerSP, uint32_t &>, 4>52Broadcaster::BroadcasterImpl::GetListeners(uint32_t event_mask,53bool include_primary) {54llvm::SmallVector<std::pair<ListenerSP, uint32_t &>, 4> listeners;55size_t max_count = m_listeners.size();56if (include_primary)57max_count++;58listeners.reserve(max_count);5960for (auto it = m_listeners.begin(); it != m_listeners.end();) {61lldb::ListenerSP curr_listener_sp(it->first.lock());62if (curr_listener_sp) {63if (it->second & event_mask)64listeners.emplace_back(std::move(curr_listener_sp), it->second);65++it;66} else67// If our listener_wp didn't resolve, then we should remove this entry.68it = m_listeners.erase(it);69}70if (include_primary && m_primary_listener_sp)71listeners.emplace_back(m_primary_listener_sp, m_primary_listener_mask);7273return listeners;74}7576bool Broadcaster::BroadcasterImpl::HasListeners(uint32_t event_mask) {77if (m_primary_listener_sp)78return true;79for (auto it = m_listeners.begin(); it != m_listeners.end(); it++) {80// Don't return a listener if the other end of the WP is gone:81lldb::ListenerSP curr_listener_sp(it->first.lock());82if (curr_listener_sp && (it->second & event_mask))83return true;84}85return false;86}8788void Broadcaster::BroadcasterImpl::Clear() {89std::lock_guard<std::mutex> guard(m_listeners_mutex);9091// Make sure the listener forgets about this broadcaster. We do this in the92// broadcaster in case the broadcaster object initiates the removal.93for (auto &pair : GetListeners())94pair.first->BroadcasterWillDestruct(&m_broadcaster);9596m_listeners.clear();97m_primary_listener_sp.reset();98}99100Broadcaster *Broadcaster::BroadcasterImpl::GetBroadcaster() {101return &m_broadcaster;102}103104bool Broadcaster::BroadcasterImpl::GetEventNames(105Stream &s, uint32_t event_mask, bool prefix_with_broadcaster_name) const {106uint32_t num_names_added = 0;107if (event_mask && !m_event_names.empty()) {108event_names_map::const_iterator end = m_event_names.end();109for (uint32_t bit = 1u, mask = event_mask; mask != 0 && bit != 0;110bit <<= 1, mask >>= 1) {111if (mask & 1) {112event_names_map::const_iterator pos = m_event_names.find(bit);113if (pos != end) {114if (num_names_added > 0)115s.PutCString(", ");116117if (prefix_with_broadcaster_name) {118s.PutCString(GetBroadcasterName());119s.PutChar('.');120}121s.PutCString(pos->second);122++num_names_added;123}124}125}126}127return num_names_added > 0;128}129130void Broadcaster::AddInitialEventsToListener(131const lldb::ListenerSP &listener_sp, uint32_t requested_events) {}132133uint32_t134Broadcaster::BroadcasterImpl::AddListener(const lldb::ListenerSP &listener_sp,135uint32_t event_mask) {136if (!listener_sp)137return 0;138139std::lock_guard<std::mutex> guard(m_listeners_mutex);140141// See if we already have this listener, and if so, update its mask142143bool handled = false;144145if (listener_sp == m_primary_listener_sp)146// This already handles all bits so just return the mask:147return event_mask;148149for (auto &pair : GetListeners(UINT32_MAX, false)) {150if (pair.first == listener_sp) {151handled = true;152pair.second |= event_mask;153m_broadcaster.AddInitialEventsToListener(listener_sp, event_mask);154break;155}156}157158if (!handled) {159// Grant a new listener the available event bits160m_listeners.push_back(161std::make_pair(lldb::ListenerWP(listener_sp), event_mask));162163// Individual broadcasters decide whether they have outstanding data when a164// listener attaches, and insert it into the listener with this method.165m_broadcaster.AddInitialEventsToListener(listener_sp, event_mask);166}167168// Return the event bits that were granted to the listener169return event_mask;170}171172bool Broadcaster::BroadcasterImpl::EventTypeHasListeners(uint32_t event_type) {173std::lock_guard<std::mutex> guard(m_listeners_mutex);174175if (!m_hijacking_listeners.empty() && event_type & m_hijacking_masks.back())176return true;177178// The primary listener listens for all event bits:179if (m_primary_listener_sp)180return true;181182return HasListeners(event_type);183}184185bool Broadcaster::BroadcasterImpl::RemoveListener(186lldb_private::Listener *listener, uint32_t event_mask) {187if (!listener)188return false;189190if (listener == m_primary_listener_sp.get()) {191// Primary listeners listen for all the event bits for their broadcaster,192// so remove this altogether if asked:193m_primary_listener_sp.reset();194return true;195}196197std::lock_guard<std::mutex> guard(m_listeners_mutex);198for (auto it = m_listeners.begin(); it != m_listeners.end();) {199lldb::ListenerSP curr_listener_sp(it->first.lock());200201if (!curr_listener_sp) {202// The weak pointer for this listener didn't resolve, lets' prune it203// as we go.204it = m_listeners.erase(it);205continue;206}207208if (curr_listener_sp.get() == listener) {209it->second &= ~event_mask;210// If we removed all the event bits from a listener, remove it from211// the list as well.212if (!it->second)213m_listeners.erase(it);214return true;215}216it++;217}218return false;219}220221bool Broadcaster::BroadcasterImpl::RemoveListener(222const lldb::ListenerSP &listener_sp, uint32_t event_mask) {223return RemoveListener(listener_sp.get(), event_mask);224}225226void Broadcaster::BroadcasterImpl::BroadcastEvent(EventSP &event_sp) {227return PrivateBroadcastEvent(event_sp, false);228}229230void Broadcaster::BroadcasterImpl::BroadcastEventIfUnique(EventSP &event_sp) {231return PrivateBroadcastEvent(event_sp, true);232}233234void Broadcaster::BroadcasterImpl::PrivateBroadcastEvent(EventSP &event_sp,235bool unique) {236// Can't add a nullptr event...237if (!event_sp)238return;239240// Update the broadcaster on this event241event_sp->SetBroadcaster(&m_broadcaster);242243const uint32_t event_type = event_sp->GetType();244245std::lock_guard<std::mutex> guard(m_listeners_mutex);246247ListenerSP hijacking_listener_sp;248249if (!m_hijacking_listeners.empty()) {250assert(!m_hijacking_masks.empty());251hijacking_listener_sp = m_hijacking_listeners.back();252if ((event_type & m_hijacking_masks.back()) == 0)253hijacking_listener_sp.reset();254}255256Log *log = GetLog(LLDBLog::Events);257if (!log && event_sp->GetData())258log = event_sp->GetData()->GetLogChannel();259260if (log) {261StreamString event_description;262event_sp->Dump(&event_description);263LLDB_LOG(log,264"{0:x} Broadcaster(\"{1}\")::BroadcastEvent (event_sp = {2}, "265"unique={3}) hijack = {4:x}",266static_cast<void *>(this), GetBroadcasterName(),267event_description.GetData(), unique,268static_cast<void *>(hijacking_listener_sp.get()));269}270ListenerSP primary_listener_sp271= hijacking_listener_sp ? hijacking_listener_sp : m_primary_listener_sp;272273if (primary_listener_sp) {274if (unique && primary_listener_sp->PeekAtNextEventForBroadcasterWithType(275&m_broadcaster, event_type))276return;277// Add the pending listeners but not if the event is hijacked, since that278// is given sole access to the event stream it is hijacking.279// Make sure to do this before adding the event to the primary or it might280// start handling the event before we're done adding all the pending281// listeners.282// Also, don't redo the check for unique here, since otherwise that could283// be racy, and if we send the event to the primary listener then we SHOULD284// send it to the secondary listeners or they will get out of sync with the285// primary listener.286if (!hijacking_listener_sp) {287for (auto &pair : GetListeners(event_type, false))288event_sp->AddPendingListener(pair.first);289}290primary_listener_sp->AddEvent(event_sp);291} else {292for (auto &pair : GetListeners(event_type)) {293if (unique && pair.first->PeekAtNextEventForBroadcasterWithType(294&m_broadcaster, event_type))295continue;296297pair.first->AddEvent(event_sp);298}299}300}301302void Broadcaster::BroadcasterImpl::BroadcastEvent(uint32_t event_type) {303auto event_sp = std::make_shared<Event>(event_type, /*data = */ nullptr);304PrivateBroadcastEvent(event_sp, false);305}306307void Broadcaster::BroadcasterImpl::BroadcastEvent(308uint32_t event_type, const lldb::EventDataSP &event_data_sp) {309auto event_sp = std::make_shared<Event>(event_type, event_data_sp);310PrivateBroadcastEvent(event_sp, false);311}312313void Broadcaster::BroadcasterImpl::BroadcastEventIfUnique(uint32_t event_type) {314auto event_sp = std::make_shared<Event>(event_type, /*data = */ nullptr);315PrivateBroadcastEvent(event_sp, true);316}317318void Broadcaster::BroadcasterImpl::SetPrimaryListener(lldb::ListenerSP319listener_sp) {320// This might have already been added as a normal listener, make sure we321// don't hold two copies.322RemoveListener(listener_sp.get(), UINT32_MAX);323m_primary_listener_sp = listener_sp;324325}326327bool Broadcaster::BroadcasterImpl::HijackBroadcaster(328const lldb::ListenerSP &listener_sp, uint32_t event_mask) {329std::lock_guard<std::mutex> guard(m_listeners_mutex);330331Log *log = GetLog(LLDBLog::Events);332LLDB_LOG(333log,334"{0} Broadcaster(\"{1}\")::HijackBroadcaster (listener(\"{2}\")={3})",335static_cast<void *>(this), GetBroadcasterName(),336listener_sp->m_name.c_str(), static_cast<void *>(listener_sp.get()));337m_hijacking_listeners.push_back(listener_sp);338m_hijacking_masks.push_back(event_mask);339return true;340}341342bool Broadcaster::BroadcasterImpl::IsHijackedForEvent(uint32_t event_mask) {343std::lock_guard<std::mutex> guard(m_listeners_mutex);344345if (!m_hijacking_listeners.empty())346return (event_mask & m_hijacking_masks.back()) != 0;347return false;348}349350const char *Broadcaster::BroadcasterImpl::GetHijackingListenerName() {351if (m_hijacking_listeners.size()) {352return m_hijacking_listeners.back()->GetName();353}354return nullptr;355}356357void Broadcaster::BroadcasterImpl::RestoreBroadcaster() {358std::lock_guard<std::mutex> guard(m_listeners_mutex);359360if (!m_hijacking_listeners.empty()) {361ListenerSP listener_sp = m_hijacking_listeners.back();362Log *log = GetLog(LLDBLog::Events);363LLDB_LOG(log,364"{0} Broadcaster(\"{1}\")::RestoreBroadcaster (about to pop "365"listener(\"{2}\")={3})",366static_cast<void *>(this), GetBroadcasterName(),367listener_sp->m_name.c_str(),368static_cast<void *>(listener_sp.get()));369m_hijacking_listeners.pop_back();370}371if (!m_hijacking_masks.empty())372m_hijacking_masks.pop_back();373}374375llvm::StringRef Broadcaster::GetBroadcasterClass() const {376static constexpr llvm::StringLiteral class_name("lldb.anonymous");377return class_name;378}379380bool BroadcastEventSpec::operator<(const BroadcastEventSpec &rhs) const {381if (GetBroadcasterClass() == rhs.GetBroadcasterClass()) {382return GetEventBits() < rhs.GetEventBits();383}384return GetBroadcasterClass() < rhs.GetBroadcasterClass();385}386387BroadcasterManager::BroadcasterManager() : m_manager_mutex() {}388389lldb::BroadcasterManagerSP BroadcasterManager::MakeBroadcasterManager() {390return lldb::BroadcasterManagerSP(new BroadcasterManager());391}392393uint32_t BroadcasterManager::RegisterListenerForEventsNoLock(394const lldb::ListenerSP &listener_sp, const BroadcastEventSpec &event_spec) {395collection::iterator iter = m_event_map.begin(), end_iter = m_event_map.end();396uint32_t available_bits = event_spec.GetEventBits();397398auto class_matches = [&event_spec](const event_listener_key &input) -> bool {399return input.first.GetBroadcasterClass() ==400event_spec.GetBroadcasterClass();401};402403while (iter != end_iter &&404(iter = find_if(iter, end_iter, class_matches)) != end_iter) {405available_bits &= ~((*iter).first.GetEventBits());406iter++;407}408409if (available_bits != 0) {410m_event_map.insert(event_listener_key(411BroadcastEventSpec(event_spec.GetBroadcasterClass(), available_bits),412listener_sp));413m_listeners.insert(listener_sp);414}415416return available_bits;417}418419bool BroadcasterManager::UnregisterListenerForEventsNoLock(420const lldb::ListenerSP &listener_sp, const BroadcastEventSpec &event_spec) {421bool removed_some = false;422423if (m_listeners.erase(listener_sp) == 0)424return false;425426auto listener_matches_and_shared_bits =427[&listener_sp, &event_spec](const event_listener_key &input) -> bool {428return input.first.GetBroadcasterClass() ==429event_spec.GetBroadcasterClass() &&430(input.first.GetEventBits() & event_spec.GetEventBits()) != 0 &&431input.second == listener_sp;432};433std::vector<BroadcastEventSpec> to_be_readded;434uint32_t event_bits_to_remove = event_spec.GetEventBits();435436// Go through the map and delete the exact matches, and build a list of437// matches that weren't exact to re-add:438for (auto iter = m_event_map.begin(), end = m_event_map.end();;) {439iter = find_if(iter, end, listener_matches_and_shared_bits);440if (iter == end)441break;442uint32_t iter_event_bits = (*iter).first.GetEventBits();443removed_some = true;444445if (event_bits_to_remove != iter_event_bits) {446uint32_t new_event_bits = iter_event_bits & ~event_bits_to_remove;447to_be_readded.emplace_back(event_spec.GetBroadcasterClass(),448new_event_bits);449}450iter = m_event_map.erase(iter);451}452453// Okay now add back the bits that weren't completely removed:454for (const auto &event : to_be_readded) {455m_event_map.insert(event_listener_key(event, listener_sp));456}457458return removed_some;459}460461ListenerSP BroadcasterManager::GetListenerForEventSpec(462const BroadcastEventSpec &event_spec) const {463std::lock_guard<std::mutex> guard(m_manager_mutex);464465auto event_spec_matches =466[&event_spec](const event_listener_key &input) -> bool {467return input.first.IsContainedIn(event_spec);468};469470auto iter = llvm::find_if(m_event_map, event_spec_matches);471if (iter != m_event_map.end())472return (*iter).second;473474return nullptr;475}476477void BroadcasterManager::RemoveListener(Listener *listener) {478std::lock_guard<std::mutex> guard(m_manager_mutex);479auto listeners_predicate =480[&listener](const lldb::ListenerSP &input) -> bool {481return input.get() == listener;482};483484if (auto iter = llvm::find_if(m_listeners, listeners_predicate);485iter != m_listeners.end())486m_listeners.erase(iter);487488auto events_predicate = [listener](const event_listener_key &input) -> bool {489return input.second.get() == listener;490};491492// TODO: use 'std::map::erase_if' when moving to c++20.493for (auto iter = m_event_map.begin(), end = m_event_map.end();;) {494iter = find_if(iter, end, events_predicate);495if (iter == end)496break;497498iter = m_event_map.erase(iter);499}500}501502void BroadcasterManager::RemoveListener(const lldb::ListenerSP &listener_sp) {503std::lock_guard<std::mutex> guard(m_manager_mutex);504505auto listener_matches =506[&listener_sp](const event_listener_key &input) -> bool {507return input.second == listener_sp;508};509510if (m_listeners.erase(listener_sp) == 0)511return;512513// TODO: use 'std::map::erase_if' when moving to c++20.514for (auto iter = m_event_map.begin(), end_iter = m_event_map.end();;) {515iter = find_if(iter, end_iter, listener_matches);516if (iter == end_iter)517break;518519iter = m_event_map.erase(iter);520}521}522523void BroadcasterManager::SignUpListenersForBroadcaster(524Broadcaster &broadcaster) {525std::lock_guard<std::mutex> guard(m_manager_mutex);526527collection::iterator iter = m_event_map.begin(), end_iter = m_event_map.end();528529auto class_matches = [&broadcaster](const event_listener_key &input) -> bool {530return input.first.GetBroadcasterClass() ==531broadcaster.GetBroadcasterClass();532};533534while (iter != end_iter &&535(iter = find_if(iter, end_iter, class_matches)) != end_iter) {536(*iter).second->StartListeningForEvents(&broadcaster,537(*iter).first.GetEventBits());538iter++;539}540}541542void BroadcasterManager::Clear() {543std::lock_guard<std::mutex> guard(m_manager_mutex);544545for (auto &listener : m_listeners)546listener->BroadcasterManagerWillDestruct(this->shared_from_this());547m_listeners.clear();548m_event_map.clear();549}550551552