1 //===-- Broadcaster.cpp ---------------------------------------------------===//
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
7 //===----------------------------------------------------------------------===//
9 #include "lldb/Utility/Broadcaster.h"
10 #include "lldb/Utility/Event.h"
11 #include "lldb/Utility/LLDBLog.h"
12 #include "lldb/Utility/Listener.h"
13 #include "lldb/Utility/Stream.h"
14 #include "lldb/Utility/StreamString.h"
24 using namespace lldb_private
;
26 Broadcaster::Broadcaster(BroadcasterManagerSP manager_sp
, std::string name
)
27 : m_broadcaster_sp(std::make_shared
<BroadcasterImpl
>(*this)),
28 m_manager_sp(std::move(manager_sp
)), m_broadcaster_name(std::move(name
)) {
29 Log
*log
= GetLog(LLDBLog::Object
);
30 LLDB_LOG(log
, "{0} Broadcaster::Broadcaster(\"{1}\")",
31 static_cast<void *>(this), GetBroadcasterName());
34 Broadcaster::BroadcasterImpl::BroadcasterImpl(Broadcaster
&broadcaster
)
35 : m_broadcaster(broadcaster
), m_listeners(), m_listeners_mutex(),
36 m_hijacking_listeners(), m_hijacking_masks() {}
38 Broadcaster::~Broadcaster() {
39 Log
*log
= GetLog(LLDBLog::Object
);
40 LLDB_LOG(log
, "{0} Broadcaster::~Broadcaster(\"{1}\")",
41 static_cast<void *>(this), GetBroadcasterName());
46 void Broadcaster::CheckInWithManager() {
48 m_manager_sp
->SignUpListenersForBroadcaster(*this);
52 llvm::SmallVector
<std::pair
<ListenerSP
, uint32_t &>, 4>
53 Broadcaster::BroadcasterImpl::GetListeners(uint32_t event_mask
,
54 bool include_primary
) {
55 llvm::SmallVector
<std::pair
<ListenerSP
, uint32_t &>, 4> listeners
;
56 size_t max_count
= m_listeners
.size();
59 listeners
.reserve(max_count
);
61 for (auto it
= m_listeners
.begin(); it
!= m_listeners
.end();) {
62 lldb::ListenerSP
curr_listener_sp(it
->first
.lock());
63 if (curr_listener_sp
) {
64 if (it
->second
& event_mask
)
65 listeners
.emplace_back(std::move(curr_listener_sp
), it
->second
);
68 // If our listener_wp didn't resolve, then we should remove this entry.
69 it
= m_listeners
.erase(it
);
71 if (include_primary
&& m_primary_listener_sp
)
72 listeners
.emplace_back(m_primary_listener_sp
, m_primary_listener_mask
);
77 bool Broadcaster::BroadcasterImpl::HasListeners(uint32_t event_mask
) {
78 if (m_primary_listener_sp
)
80 for (auto it
= m_listeners
.begin(); it
!= m_listeners
.end(); it
++) {
81 // Don't return a listener if the other end of the WP is gone:
82 lldb::ListenerSP
curr_listener_sp(it
->first
.lock());
83 if (curr_listener_sp
&& (it
->second
& event_mask
))
89 void Broadcaster::BroadcasterImpl::Clear() {
90 std::lock_guard
<std::recursive_mutex
> guard(m_listeners_mutex
);
92 // Make sure the listener forgets about this broadcaster. We do this in the
93 // broadcaster in case the broadcaster object initiates the removal.
94 for (auto &pair
: GetListeners())
95 pair
.first
->BroadcasterWillDestruct(&m_broadcaster
);
98 m_primary_listener_sp
.reset();
101 Broadcaster
*Broadcaster::BroadcasterImpl::GetBroadcaster() {
102 return &m_broadcaster
;
105 bool Broadcaster::BroadcasterImpl::GetEventNames(
106 Stream
&s
, uint32_t event_mask
, bool prefix_with_broadcaster_name
) const {
107 uint32_t num_names_added
= 0;
108 if (event_mask
&& !m_event_names
.empty()) {
109 event_names_map::const_iterator end
= m_event_names
.end();
110 for (uint32_t bit
= 1u, mask
= event_mask
; mask
!= 0 && bit
!= 0;
111 bit
<<= 1, mask
>>= 1) {
113 event_names_map::const_iterator pos
= m_event_names
.find(bit
);
115 if (num_names_added
> 0)
118 if (prefix_with_broadcaster_name
) {
119 s
.PutCString(GetBroadcasterName());
122 s
.PutCString(pos
->second
);
128 return num_names_added
> 0;
131 void Broadcaster::AddInitialEventsToListener(
132 const lldb::ListenerSP
&listener_sp
, uint32_t requested_events
) {}
135 Broadcaster::BroadcasterImpl::AddListener(const lldb::ListenerSP
&listener_sp
,
136 uint32_t event_mask
) {
140 std::lock_guard
<std::recursive_mutex
> guard(m_listeners_mutex
);
142 // See if we already have this listener, and if so, update its mask
144 bool handled
= false;
146 if (listener_sp
== m_primary_listener_sp
)
147 // This already handles all bits so just return the mask:
150 for (auto &pair
: GetListeners(UINT32_MAX
, false)) {
151 if (pair
.first
== listener_sp
) {
153 pair
.second
|= event_mask
;
154 m_broadcaster
.AddInitialEventsToListener(listener_sp
, event_mask
);
160 // Grant a new listener the available event bits
161 m_listeners
.push_back(
162 std::make_pair(lldb::ListenerWP(listener_sp
), event_mask
));
164 // Individual broadcasters decide whether they have outstanding data when a
165 // listener attaches, and insert it into the listener with this method.
166 m_broadcaster
.AddInitialEventsToListener(listener_sp
, event_mask
);
169 // Return the event bits that were granted to the listener
173 bool Broadcaster::BroadcasterImpl::EventTypeHasListeners(uint32_t event_type
) {
174 std::lock_guard
<std::recursive_mutex
> guard(m_listeners_mutex
);
176 if (!m_hijacking_listeners
.empty() && event_type
& m_hijacking_masks
.back())
179 // The primary listener listens for all event bits:
180 if (m_primary_listener_sp
)
183 return HasListeners(event_type
);
186 bool Broadcaster::BroadcasterImpl::RemoveListener(
187 lldb_private::Listener
*listener
, uint32_t event_mask
) {
191 if (listener
== m_primary_listener_sp
.get()) {
192 // Primary listeners listen for all the event bits for their broadcaster,
193 // so remove this altogether if asked:
194 m_primary_listener_sp
.reset();
198 std::lock_guard
<std::recursive_mutex
> guard(m_listeners_mutex
);
199 for (auto it
= m_listeners
.begin(); it
!= m_listeners
.end();) {
200 lldb::ListenerSP
curr_listener_sp(it
->first
.lock());
202 if (!curr_listener_sp
) {
203 // The weak pointer for this listener didn't resolve, lets' prune it
205 m_listeners
.erase(it
);
209 if (curr_listener_sp
.get() == listener
) {
210 it
->second
&= ~event_mask
;
211 // If we removed all the event bits from a listener, remove it from
214 m_listeners
.erase(it
);
222 bool Broadcaster::BroadcasterImpl::RemoveListener(
223 const lldb::ListenerSP
&listener_sp
, uint32_t event_mask
) {
224 return RemoveListener(listener_sp
.get(), event_mask
);
227 void Broadcaster::BroadcasterImpl::BroadcastEvent(EventSP
&event_sp
) {
228 return PrivateBroadcastEvent(event_sp
, false);
231 void Broadcaster::BroadcasterImpl::BroadcastEventIfUnique(EventSP
&event_sp
) {
232 return PrivateBroadcastEvent(event_sp
, true);
235 void Broadcaster::BroadcasterImpl::PrivateBroadcastEvent(EventSP
&event_sp
,
237 // Can't add a nullptr event...
241 // Update the broadcaster on this event
242 event_sp
->SetBroadcaster(&m_broadcaster
);
244 const uint32_t event_type
= event_sp
->GetType();
246 std::lock_guard
<std::recursive_mutex
> guard(m_listeners_mutex
);
248 ListenerSP hijacking_listener_sp
;
250 if (!m_hijacking_listeners
.empty()) {
251 assert(!m_hijacking_masks
.empty());
252 hijacking_listener_sp
= m_hijacking_listeners
.back();
253 if ((event_type
& m_hijacking_masks
.back()) == 0)
254 hijacking_listener_sp
.reset();
257 Log
*log
= GetLog(LLDBLog::Events
);
258 if (!log
&& event_sp
->GetData())
259 log
= event_sp
->GetData()->GetLogChannel();
262 StreamString event_description
;
263 event_sp
->Dump(&event_description
);
265 "{0:x} Broadcaster(\"{1}\")::BroadcastEvent (event_sp = {2}, "
266 "unique={3}) hijack = {4:x}",
267 static_cast<void *>(this), GetBroadcasterName(),
268 event_description
.GetData(), unique
,
269 static_cast<void *>(hijacking_listener_sp
.get()));
271 ListenerSP primary_listener_sp
272 = hijacking_listener_sp
? hijacking_listener_sp
: m_primary_listener_sp
;
274 if (primary_listener_sp
) {
275 if (unique
&& primary_listener_sp
->PeekAtNextEventForBroadcasterWithType(
276 &m_broadcaster
, event_type
))
278 // Add the pending listeners but not if the event is hijacked, since that
279 // is given sole access to the event stream it is hijacking.
280 // Make sure to do this before adding the event to the primary or it might
281 // start handling the event before we're done adding all the pending
283 if (!hijacking_listener_sp
) {
284 for (auto &pair
: GetListeners(event_type
, false)) {
285 if (unique
&& pair
.first
->PeekAtNextEventForBroadcasterWithType(
286 &m_broadcaster
, event_type
))
288 event_sp
->AddPendingListener(pair
.first
);
291 primary_listener_sp
->AddEvent(event_sp
);
293 for (auto &pair
: GetListeners(event_type
)) {
294 if (unique
&& pair
.first
->PeekAtNextEventForBroadcasterWithType(
295 &m_broadcaster
, event_type
))
298 pair
.first
->AddEvent(event_sp
);
303 void Broadcaster::BroadcasterImpl::BroadcastEvent(uint32_t event_type
,
304 EventData
*event_data
) {
305 auto event_sp
= std::make_shared
<Event
>(event_type
, event_data
);
306 PrivateBroadcastEvent(event_sp
, false);
309 void Broadcaster::BroadcasterImpl::BroadcastEvent(
310 uint32_t event_type
, const lldb::EventDataSP
&event_data_sp
) {
311 auto event_sp
= std::make_shared
<Event
>(event_type
, event_data_sp
);
312 PrivateBroadcastEvent(event_sp
, false);
315 void Broadcaster::BroadcasterImpl::BroadcastEventIfUnique(
316 uint32_t event_type
, EventData
*event_data
) {
317 auto event_sp
= std::make_shared
<Event
>(event_type
, event_data
);
318 PrivateBroadcastEvent(event_sp
, true);
321 void Broadcaster::BroadcasterImpl::SetPrimaryListener(lldb::ListenerSP
323 // This might have already been added as a normal listener, make sure we
324 // don't hold two copies.
325 RemoveListener(listener_sp
.get(), UINT32_MAX
);
326 m_primary_listener_sp
= listener_sp
;
330 bool Broadcaster::BroadcasterImpl::HijackBroadcaster(
331 const lldb::ListenerSP
&listener_sp
, uint32_t event_mask
) {
332 std::lock_guard
<std::recursive_mutex
> guard(m_listeners_mutex
);
334 Log
*log
= GetLog(LLDBLog::Events
);
337 "{0} Broadcaster(\"{1}\")::HijackBroadcaster (listener(\"{2}\")={3})",
338 static_cast<void *>(this), GetBroadcasterName(),
339 listener_sp
->m_name
.c_str(), static_cast<void *>(listener_sp
.get()));
340 m_hijacking_listeners
.push_back(listener_sp
);
341 m_hijacking_masks
.push_back(event_mask
);
345 bool Broadcaster::BroadcasterImpl::IsHijackedForEvent(uint32_t event_mask
) {
346 std::lock_guard
<std::recursive_mutex
> guard(m_listeners_mutex
);
348 if (!m_hijacking_listeners
.empty())
349 return (event_mask
& m_hijacking_masks
.back()) != 0;
353 const char *Broadcaster::BroadcasterImpl::GetHijackingListenerName() {
354 if (m_hijacking_listeners
.size()) {
355 return m_hijacking_listeners
.back()->GetName();
360 void Broadcaster::BroadcasterImpl::RestoreBroadcaster() {
361 std::lock_guard
<std::recursive_mutex
> guard(m_listeners_mutex
);
363 if (!m_hijacking_listeners
.empty()) {
364 ListenerSP listener_sp
= m_hijacking_listeners
.back();
365 Log
*log
= GetLog(LLDBLog::Events
);
367 "{0} Broadcaster(\"{1}\")::RestoreBroadcaster (about to pop "
368 "listener(\"{2}\")={3})",
369 static_cast<void *>(this), GetBroadcasterName(),
370 listener_sp
->m_name
.c_str(),
371 static_cast<void *>(listener_sp
.get()));
372 m_hijacking_listeners
.pop_back();
374 if (!m_hijacking_masks
.empty())
375 m_hijacking_masks
.pop_back();
378 ConstString
&Broadcaster::GetBroadcasterClass() const {
379 static ConstString
class_name("lldb.anonymous");
383 bool BroadcastEventSpec::operator<(const BroadcastEventSpec
&rhs
) const {
384 if (GetBroadcasterClass() == rhs
.GetBroadcasterClass()) {
385 return GetEventBits() < rhs
.GetEventBits();
387 return GetBroadcasterClass() < rhs
.GetBroadcasterClass();
390 BroadcasterManager::BroadcasterManager() : m_manager_mutex() {}
392 lldb::BroadcasterManagerSP
BroadcasterManager::MakeBroadcasterManager() {
393 return lldb::BroadcasterManagerSP(new BroadcasterManager());
396 uint32_t BroadcasterManager::RegisterListenerForEvents(
397 const lldb::ListenerSP
&listener_sp
, const BroadcastEventSpec
&event_spec
) {
398 std::lock_guard
<std::recursive_mutex
> guard(m_manager_mutex
);
400 collection::iterator iter
= m_event_map
.begin(), end_iter
= m_event_map
.end();
401 uint32_t available_bits
= event_spec
.GetEventBits();
403 auto class_matches
= [&event_spec
](const event_listener_key
&input
) -> bool {
404 return input
.first
.GetBroadcasterClass() ==
405 event_spec
.GetBroadcasterClass();
408 while (iter
!= end_iter
&&
409 (iter
= find_if(iter
, end_iter
, class_matches
)) != end_iter
) {
410 available_bits
&= ~((*iter
).first
.GetEventBits());
414 if (available_bits
!= 0) {
415 m_event_map
.insert(event_listener_key(
416 BroadcastEventSpec(event_spec
.GetBroadcasterClass(), available_bits
),
418 m_listeners
.insert(listener_sp
);
421 return available_bits
;
424 bool BroadcasterManager::UnregisterListenerForEvents(
425 const lldb::ListenerSP
&listener_sp
, const BroadcastEventSpec
&event_spec
) {
426 std::lock_guard
<std::recursive_mutex
> guard(m_manager_mutex
);
427 bool removed_some
= false;
429 if (m_listeners
.erase(listener_sp
) == 0)
432 auto listener_matches_and_shared_bits
=
433 [&listener_sp
, &event_spec
](const event_listener_key
&input
) -> bool {
434 return input
.first
.GetBroadcasterClass() ==
435 event_spec
.GetBroadcasterClass() &&
436 (input
.first
.GetEventBits() & event_spec
.GetEventBits()) != 0 &&
437 input
.second
== listener_sp
;
439 std::vector
<BroadcastEventSpec
> to_be_readded
;
440 uint32_t event_bits_to_remove
= event_spec
.GetEventBits();
442 // Go through the map and delete the exact matches, and build a list of
443 // matches that weren't exact to re-add:
444 for (auto iter
= m_event_map
.begin(), end
= m_event_map
.end();;) {
445 iter
= find_if(iter
, end
, listener_matches_and_shared_bits
);
448 uint32_t iter_event_bits
= (*iter
).first
.GetEventBits();
451 if (event_bits_to_remove
!= iter_event_bits
) {
452 uint32_t new_event_bits
= iter_event_bits
& ~event_bits_to_remove
;
453 to_be_readded
.emplace_back(event_spec
.GetBroadcasterClass(),
456 iter
= m_event_map
.erase(iter
);
459 // Okay now add back the bits that weren't completely removed:
460 for (const auto &event
: to_be_readded
) {
461 m_event_map
.insert(event_listener_key(event
, listener_sp
));
467 ListenerSP
BroadcasterManager::GetListenerForEventSpec(
468 const BroadcastEventSpec
&event_spec
) const {
469 std::lock_guard
<std::recursive_mutex
> guard(m_manager_mutex
);
471 auto event_spec_matches
=
472 [&event_spec
](const event_listener_key
&input
) -> bool {
473 return input
.first
.IsContainedIn(event_spec
);
476 auto iter
= llvm::find_if(m_event_map
, event_spec_matches
);
477 if (iter
!= m_event_map
.end())
478 return (*iter
).second
;
483 void BroadcasterManager::RemoveListener(Listener
*listener
) {
484 std::lock_guard
<std::recursive_mutex
> guard(m_manager_mutex
);
485 auto listeners_predicate
=
486 [&listener
](const lldb::ListenerSP
&input
) -> bool {
487 return input
.get() == listener
;
490 if (auto iter
= llvm::find_if(m_listeners
, listeners_predicate
);
491 iter
!= m_listeners
.end())
492 m_listeners
.erase(iter
);
494 auto events_predicate
= [listener
](const event_listener_key
&input
) -> bool {
495 return input
.second
.get() == listener
;
498 // TODO: use 'std::map::erase_if' when moving to c++20.
499 for (auto iter
= m_event_map
.begin(), end
= m_event_map
.end();;) {
500 iter
= find_if(iter
, end
, events_predicate
);
504 iter
= m_event_map
.erase(iter
);
508 void BroadcasterManager::RemoveListener(const lldb::ListenerSP
&listener_sp
) {
509 std::lock_guard
<std::recursive_mutex
> guard(m_manager_mutex
);
511 auto listener_matches
=
512 [&listener_sp
](const event_listener_key
&input
) -> bool {
513 return input
.second
== listener_sp
;
516 if (m_listeners
.erase(listener_sp
) == 0)
519 // TODO: use 'std::map::erase_if' when moving to c++20.
520 for (auto iter
= m_event_map
.begin(), end_iter
= m_event_map
.end();;) {
521 iter
= find_if(iter
, end_iter
, listener_matches
);
522 if (iter
== end_iter
)
525 iter
= m_event_map
.erase(iter
);
529 void BroadcasterManager::SignUpListenersForBroadcaster(
530 Broadcaster
&broadcaster
) {
531 std::lock_guard
<std::recursive_mutex
> guard(m_manager_mutex
);
533 collection::iterator iter
= m_event_map
.begin(), end_iter
= m_event_map
.end();
535 auto class_matches
= [&broadcaster
](const event_listener_key
&input
) -> bool {
536 return input
.first
.GetBroadcasterClass() ==
537 broadcaster
.GetBroadcasterClass();
540 while (iter
!= end_iter
&&
541 (iter
= find_if(iter
, end_iter
, class_matches
)) != end_iter
) {
542 (*iter
).second
->StartListeningForEvents(&broadcaster
,
543 (*iter
).first
.GetEventBits());
548 void BroadcasterManager::Clear() {
549 std::lock_guard
<std::recursive_mutex
> guard(m_manager_mutex
);
551 for (auto &listener
: m_listeners
)
552 listener
->BroadcasterManagerWillDestruct(this->shared_from_this());